-
Notifications
You must be signed in to change notification settings - Fork 1
/
itemExcluder.js
53 lines (42 loc) · 1.17 KB
/
itemExcluder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Implement a method to effieciently exlude items from the items array, as outlined in the exlude array.
const itemList = [
{type: 'computer', color: 'green', flavor: 'apple'},
{type: 'cellphone', color: 'gold', flavor: 'orange'},
{type: 'computer', color: 'silver', flavor: 'grape'},
]
const excludeList = [
{k: 'type', v: 'cellphone'},
{k: 'color', v: 'silver'},
{k: 'color', v: 'gold'},
];
const itemExcluder = (items, exlude) => {
const excludeCache = {};
// Build exclude cache
exlude.forEach(item => {
if (excludeCache.hasOwnProperty(item.k)) {
excludeCache[item.k][item.v] = true;
} else {
const newExludeObj = {};
newExludeObj[item.v] = true
excludeCache[item.k] = newExludeObj;
}
});
// Check if any items are in the xclude cache
const filteredItems = [];
items.forEach(item => {
let filterFlag = false;
Object.keys(item).forEach(itemKey => {
if (excludeCache[itemKey]) {
if (excludeCache[itemKey][item[itemKey]] ) {
filterFlag = true
}
}
});
if (!filterFlag) {
return filteredItems.push(item);
}
});
return filteredItems;
}
const result = itemExcluder(itemList, excludeList);
console.log('result', result);