JavaScript·

18. Improve a function

  • #BFE.dev
  • #JavaScript

문제

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

1
// Given an input of array,
2
// which is made of items with >= 3 properties
3
let items = [
4
{color: 'red', type: 'tv', age: 18},
5
{color: 'silver', type: 'phone', age: 20},
6
{color: 'blue', type: 'book', age: 17}
7
]
8
// an exclude array made of key value pair
9
const excludes = [
10
{k: 'color', v: 'silver'},
11
{k: 'type', v: 'tv'},
12
...
13
]
14
function excludeItems(items, excludes) {
15
excludes.forEach( pair => {
16
items = items.filter(item => item[pair.k] === item[pair.v])
17
})
18
19
return items
20
}
  1. excludeItems 함수는 어떤 역할을 하나요?
  2. 함수가 기대대로 동작하나요?
  3. 현재 함수의 시간 복잡도는 어떤가요?
  4. 어떻게 최적화 할 수 있을까요?

선행 지식

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

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

풀이