collections-reduce3
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) {
if (context) {
iteratee = iteratee.bind(context);
}
collection = Array.from(collection);
let arr, acc;
if (isNaN(accumulator)) {
acc = collection[0];
arr = collection.slice(1);
} else {
acc = accumulator;
arr = collection;
}
for (let i=0; i<arr.length; i++) {
acc = iteratee(acc, arr[i], i, arr);
}
return acc;
/*
if (collection.length === 0) {
return accumulator;
} else {
return _.reduce(collection.slice(1), iteratee, iteratee(accumulator, collection[0], 0, collection));
}
*/
};
// test 1
var sum1 = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
console.log(sum1);
//=> 6
var sum2 = _.reduce([4, 5, 6], function(memo, num){ return memo + num; });
console.log(sum2);
//=> 6
// test 2
var pilots = [
{
id: 10,
name: "Poe Dameron",
years: 14,
},
{
id: 2,
name: "Temmin 'Snap' Wexley",
years: 30,
},
{
id: 41,
name: "Tallissan Lintra",
years: 16,
},
{
id: 99,
name: "Ello Asty",
years: 22,
}
];
var totalYears = _.reduce(pilots,function (accumulator, pilot) {
return accumulator + pilot.years;
}, 0);
console.log(totalYears);