bh2980.dev

18. Improve a function

  • #BFE.dev
  • #JavaScript

문제

아래 함수를 보고 제시된 질문에 답변을 해주세요.

// Given an input of array, 
// which is made of items with >= 3 properties
let items = [
  {color: 'red', type: 'tv', age: 18}, 
  {color: 'silver', type: 'phone', age: 20},
  {color: 'blue', type: 'book', age: 17}
];

// an exclude array made of key value pair
const excludes = [ 
  {k: 'color', v: 'silver'}, 
  {k: 'type', v: 'tv'}
];

function excludeItems(items, excludes) { 
  excludes.forEach(pair => { 
    // Logic fix: filter out items where key equals value
    items = items.filter(item => item[pair.k] !== pair.v);
  });
 
  return items;
}
  1. excludeItems 함수는 어떤 역할을 하나요?
  2. 함수가 기대대로 동작하나요?
  3. 현재 함수의 시간 복잡도는 어떤가요?
  4. 어떻게 최적화 할 수 있을까요?

선행 지식

  1. Object.entries() vs Set.prototype.entries()

    Object.entries()는 새로운 배열을 만들어서 return하는 반면, Set.prototype.entries()는 순회할 수 있도록 만드는 이터레이터 객체를 만들어 return한다.

풀이