collections-some2
by shan10213223
JavaScript
var _ = {};
_.every = function (collection, predicate, context) {
if (context) {
predicate = predicate.bind(context);
}
if (Array.isArray(collection)) {
for (let i=0; i<collection.length; i++) {
if (Object.prototype.hasOwnProperty.call(collection, i)) {
if (collection[i] == null) {
return false;
} else if (predicate(collection[i], i, collection) === false) {
return false;
}
}
}
} else {
for (let key in collection) {
if (Object.prototype.hasOwnProperty.call(collection, key)) {
if (collection[key] == null) {
return false;
} else if (predicate(collection[key], key, collection) === false) {
return false;
}
}
}
}
return true;
};
// _.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().
//https://stackoverflow.com/questions/18157348/how-to-solve-some-using-every
_.some = function (collection, predicate, context) {
if (context) {
predicate = predicate.bind(context);
}
return !(_.every(collection, function (item, key) {
return !(predicate(item, key, collection));
}));
};
// 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);