function each(collection, callback) {
if (Array.isArray(collection)) {
for (var i = 0; i < collection.length; i++) {
callback(collection[i]);
}
}
else {
for (var prop in collection) {
callback(collection[prop], prop, collection);
}
}
}
var array = [1, 2, 3, 4, 5];
function reduce(collection, callback, initial) {
var current = initial;
each(collection, function(current, e) {
current = callback(current, e);
})
return current;
}
console.log(reduce(array, function(a, b) { return a + b }, 0)); -->>> 0
I'm trying to rewrite the underscore each/reduce functions, and use the each function in reduce. I know that I have a mistake in there-- (current should not be in the each callback function) it should be just be
each(collection, function(e) {
current = callback(current, e);
})
and that returns 15 as it should, but why does it return 0 when you do add that current in there as a parameter? Shouldn't it just return NaN? As the last part of the loop will try to add 5 and undefined which is NaN.
.hasOwnProperty()in youreach()function for the case when the collection is not an arraycurrentas a parameter, you override the outer scope variable, and end up never changing it's initial valuepropandcollectionto the callback in the case of an object, shouldn't you also passiandcollectionin the case of an array?