Better readability could be achieved using array.filter
, since it creates the array for you and all you have to do is return true
or false
. No need to create an array, do the comparison and push yourself.
In the same way when checking for the values, Object.keys
can be used with array.every
to iterate through your constraints and see if each of the current item's keys match the constraint.
Also, I wouldn't call it source
. It's not a source of anything. It's more of a "constraint" for your collection. So I'd call it that way instead.
In terms of performance, array iteration functions are slower than your average for
loop (older APIs will tend to be more optimized). However, in terms of readability, these array APIs really shorten your code.
function where(collection, constraint){
// filter creates an array of items whose callback returns true for them
return collection.filter(function(collectionItem){
// every returns true when every item's callback returns true
return Object.keys(constraint).every(function(key){
return collectionItem.hasOwnProperty(key) && constraint[key] === collectionItem[key];
});
});
}
var a = where([{ "a": 1 }, { "a": 1 }, { "a": 1, "b": 3 }], { "a": 1});
var b = where([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 })
document.write(JSON.stringify(a));
document.write('<br>');
document.write(JSON.stringify(b));
The code can further be simplified by taking advantage of ES6 arrow functions.
function where(collection, constraint){
return collection.filter(collectionItem =>
Object.keys(constraint).every(key =>
collectionItem.hasOwnProperty(key) && constraint[key] === collectionItem[key]));
}
var a = where([{ "a": 1 }, { "a": 1 }, { "a": 1, "b": 3 }], { "a": 1});
var b = where([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 })
document.write(JSON.stringify(a));
document.write('<br>');
document.write(JSON.stringify(b));