collections-reduce1
by shan10213223
JavaScript
var _ = {};
// _.reduce(collection, iteratee, [accumulator], [context])
// Reduce boils down a collection of values into a single value.
// Accumulator is the initial state of the reduction,
// and each successive step of it should be returned by iteratee.
// Iteratee is passed four arguments: (accumulator, element, index|key, collection),
// and bound to the context if one is passed. If no accumulator is passed
// to the initial invocation of reduce, iteratee is not invoked on the first element,
// and the first element is instead passed as accumulator for the next invocation.
_.reduce = function (collection, iteratee, accumulator, context) {
let results;
// if array
if (Array.isArray(collection)) {
if (accumulator !== undefined) {
results = accumulator;
for (let i=0; i<collection.length; i++) {
results = iteratee(results, collection[i]);
}
} else {
results = collection[0];
for (let i=1; i<collection.length; i++) {
results = iteratee(results, collection[i]);
}
}
// if object
} else {
results = accumulator;
for (let key in collection) {
results = iteratee(results, collection[key], key);
}
}
return results;
};
// test 1
var sum1 = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
console.log(sum1);
//=> 6
var sum2 = _.reduce([1, 2, 3], function(memo, num){ return memo + num; });
console.log(sum2);
//=> 6