collections-some1
by shan10213223
JavaScript
var _ = {};
// _.every(collection, [predicate], [context])
// Returns true if all values in the collection pass the predicate truth test.
// Predicate is called with three arguments:
// (element, index|key, collection), and bound to the context if one is passed.
// Short-circuits and stops traversing the list if a false element is found.
// TIP: without the short-circuiting you could reuse _.reduce(). Can you figure how?
// Because of the short-circuiting though, you need to re-implement a modified _.each().
_.some = function (collection, predicate, context) {
let results = false;
collection.forEach(function(element) {
if (predicate(element)) {
results = true;
}
});
return results;
};
// tests
let test1 = _.some([2, 4, 5], function(num) { return num % 2 == 0; });
console.log(test1);
//=> false
let test2 = _.some([2, 4, 6], function(num) { return num % 2 == 0; });
console.log(test2);
let test3 = _.some([1, 3, 5], function(num) { return num % 2 == 0; });
console.log(test3);