Created
March 4, 2018 01:08
-
-
Save victorouse/eda118b8d39b7618147e5414c8c81155 to your computer and use it in GitHub Desktop.
Facebook Interview: Filter Properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function createExcludedMap(excludes) { | |
return excludes.reduce((map, pair) => { | |
const values = map.get(pair.k); | |
if (values) { | |
values.push(pair.v); | |
return map.set(pair.k, values); | |
} | |
return map.set(pair.k, [pair.v]); | |
}, new Map()); | |
} | |
/* | |
function excludeItems(items, excludes) { | |
excludes.forEach((pair, outer) => { | |
items = items.filter((item, inner) => { | |
return item[pair.k] !== pair.v; | |
}); | |
}); | |
return items; | |
} | |
*/ | |
/* | |
function excludeItems(items, excludes) { | |
const included = []; | |
for (const item of items) { | |
let excluded = false; | |
for (const [key, values] of excludesMap) { | |
if (item[key] && values.includes(item[key])) { | |
excluded = true; | |
break; | |
} | |
} | |
if (!excluded) { | |
included.push(item); | |
} | |
} | |
return included; | |
} | |
*/ | |
function excludeItems(items, excludes) { | |
for (const item of items) { | |
for (const [key, values] of excludesMap) { | |
items = items.filter((item) => !values.includes(item[key])); | |
} | |
} | |
return items; | |
} | |
const items = [ | |
{ color: 'red', type: 'tv', age: 18 }, | |
{ color: 'red', type: 'phone', age: 20 }, | |
{ color: 'silver', type: 'tv', age: 18 }, | |
{ color: 'silver', type: 'phone', age: 20 } | |
]; | |
const excludes = [ | |
{ k: 'color', v: 'red' }, | |
{ k: 'color', v: 'blue' }, | |
{ k: 'type', v: 'phone' }, | |
]; | |
/* | |
const excludesMap = new Map( | |
['color', ['red', 'blue']], | |
['type', ['phone']] | |
); | |
*/ | |
const excludesMap = createExcludedMap(excludes); | |
console.log('result', excludeItems(items, excludesMap)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Rather than chaining items on an array for
excludesMap
, you could use an obj with O(1) accessThis is how I did it:
Breaking down:
In the 1st iteration, you get: