Skip to content

Instantly share code, notes, and snippets.

@Noitidart
Last active January 27, 2019 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Noitidart/11be7e2c587e7be971f3bf1f5a7a2a87 to your computer and use it in GitHub Desktop.
Save Noitidart/11be7e2c587e7be971f3bf1f5a7a2a87 to your computer and use it in GitHub Desktop.
(function() {
let items = [
{color: 'red', type: 'tv', age: 18},
{color: 'silver', type: 'phone', age: 20}
]
const excludes = [
{k: 'color', v: 'silver'},
{k: 'type', v: 'tv'},
]
function excludeItems(items, excludes) {
excludes.forEach(pair => {
items = items.filter( // O(n) // n is length of excludes array
item => item[pair.k] === item[pair.v] // O(m) // m is length of items array
);
});
return items;
}
console.log(excludeItems(items, excludes));
})()
(function() {
let items = [
{color: 'red', type: 'tv', age: 18},
{color: 'silver', type: 'phone', age: 20}
]
const excludes = [
{k: 'color', v: 'silver'},
{k: 'type', v: 'tv'},
]
function turnIntoMap(arr){
var hash = {};
arr.forEach(function(val){
if(hash[val.k]){
hash[val.k][val.v] = 1
} else {
hash[val.k] = {};
hash[val.k][val.v] = 1
}
});
return hash;
}
const excludeMap = turnIntoMap(excludes);
console.log('excludeMap:', excludeMap);
function excludeItems(items, excludes) {
const testKeys = Object.keys(excludes);
items = items.filter( // o(n) // n is length of items array
item => {
for (const testKey of testKeys) { // o(m) // m is length of excludes array (assuming the array had unique key in each item - worst case)
if (excludes[testKey][item[testKey]]) {
return false;
}
}
}
);
return items;
}
console.log(excludeItems(items, excludeMap));
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment