collections-every1
by shan10213223
JavaScript
var _ = {};
_.each = function (collection, iteratee, context) {
if (context) {
iteratee = iteratee.bind(context);
}
if (Array.isArray(collection)) {
for (let i=0; i<collection.length; i++) {
if (Object.prototype.hasOwnProperty.call(collection, i)) {
iteratee(collection[i], i, collection);
}
}
} else {
for (let key in collection) {
if (Object.prototype.hasOwnProperty.call(collection, key)) {
iteratee(collection[key], key, collection);
}
}
}
return collection;
};
_.reduce = function (collection, iteratee, accumulator, context) {
if (context) {
iteratee = iteratee.bind(context);
}
_.each(collection, function (item, key) {
if (accumulator === undefined) {
accumulator = item;
} else {
accumulator = iteratee(accumulator, item, key, collection);
}
});
return accumulator;
};
// _.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().
_.every = function (collection, predicate, context) {
//let results = [];
let flag = true;
//console.log(collection);
if (collection.length === 0 || collection.length === undefined || collection == null) {
return flag;
}
_.each(collection, function (item, key) {
console.log(item);
if (item === undefined || item === null || (predicate(item, key, collection) === false)) {
flag = false;
return;
//return flag;
}
console.log('pass');
//results.push(predicate(item, key, collection));
});
return flag;
/*for (let i=0; i<results.length; i++)...