Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//Given input:
// could be potentially more than 3 keys in the object above
// items = [
// {color: 'red', type: 'tv', age: 18},
// {color: 'silver', type: 'phone', age: 20}
// ...
// ]
// excludes = [
// {k: 'color', v: 'silver'},
// {k: 'type', v: 'tv'},
// ....
// ]
// function excludeItems(items, excludes) {
// excludes.forEach(pair => {
// items = items.filter(item => item[pair.k] === item[pair.v]);
// });
// return items;
// }
// 1. Describe what this function is doing...
// Answer: base on the function name/signature, the function receives lists of items and returns a filtered version of it based on list
// of items to be excluded from original list.
// 2. What is wrong with that function ?
// Answer:
// 1. Input Case handling - what if excludes is not iterable?
// 2. Logic error: Excludes are defined as array of objects which have 2 properties - k and v as key and value of it respectively.
// Hence in filter check, it is supposed to check if item's property (according to key) has the same value, such as:
// item[pair.k] === pair.v
// item[pair.k] === item[pair.v] means if value of item's property mapped to pair.k equals to value of items' property mapped to pair.v
// Also it's supposed to return filtered list WITHOUT excludes, which mean the check should !==, not ===.
// 3. How would you optimize it ?
// Answer: 1. Use normal loop instead of ForEach, which is well-known for being slow.
// 2. Provide the correct check condition
// 3. Input case check
// 4. Excludes don't need to be an array, it can be map of <key, value> in which value is array of values need to be excluded
// which is map to key. For example:
// var excludes = new Map([['color', ['silver', 'red', ...]], ['type', []]);
function excludeItems(items, excludes){
if (excludes && excludes instanceof Map){
for(var [key, arryOfValues] of excludes){
items = items.filter((item) => arryOfValues.indexOf(item[key]) === -1);
}
}
return items;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment