Last active
January 27, 2019 18:15
-
-
Save Noitidart/11be7e2c587e7be971f3bf1f5a7a2a87 to your computer and use it in GitHub Desktop.
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() { | |
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)); | |
})() |
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() { | |
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