Created
April 2, 2020 21:36
-
-
Save imjakechapman/47297287c50a5d429ead143c6343295e to your computer and use it in GitHub Desktop.
Facebook Interview Question
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
const items = [ | |
{type: 'phone', name: 'iPhone', color: 'gold'}, | |
{type: 'laptop', name: 'Chromebook', color: 'gray'}, | |
]; | |
const excludes = [ | |
{k: 'color', v: 'gold'}, | |
{k: 'color', v: 'silver'}, | |
{k: 'type', v: 'tv'} | |
]; | |
// O(n * m) | |
// Before new solution | |
// excludes.forEach(function(pair) { | |
// items = items.filter((item) => item[pair.k] !== pair.v); | |
// }); | |
// return items; | |
// O(n + m) | |
function applyFilters(items, excludes) { | |
const lookup = excludes.reduce((acc, cur) => { | |
const { k, v } = cur; | |
if(acc[k]) { | |
acc[k][v] = v; | |
} else { | |
acc[k] = {}; | |
acc[k][v] = v; | |
} | |
return acc; | |
}, {}); | |
return items.filter(item => { | |
const lookupKeys = Object.keys(lookup); | |
const itemKeys = Object.keys(item); | |
for(let i = 0; i < lookupKeys.length; i++) { | |
let lk = lookupKeys[i]; | |
if(item.hasOwnProperty(lk) && lookup[lk][item[lk]]) { | |
return false; | |
} | |
} | |
return true; | |
}); | |
} | |
const filtered = applyFilters(items, excludes); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment