I am working on rewriting the underlying code for some Underscore.js functions. Re-writing the reduce function has been causing a lot of headaches. I have been able to re-write it two different ways, both work, but I was wondering which version is more efficient and if I could improve either one?
Reduce function one:
function reduce(collection, func, accumulator) {
var i = 0;
var isCollection = Array.isArray(collection);
if (arguments.length < 3) {
isCollection ? accumulator = collection[0] : Object.keys(collection)[0];
i++;
}
if (isCollection) {
for (; i < collection.length; i++) {
accumulator = func(accumulator, collection[i]);
}
} else {
for (var key in collection) {
accumulator = func(accumulator, collection[key]);
}
}
return accumulator;
};
var numbers = [1, 2, 3];
var sum = reduce(numbers, function(total, number){
return total + number;
}, 0); // should be 6
console.log(sum);
Reduce function two:
function reduceTwo(collection, func, accumulator) {
var args = arguments.length < 3;
each(collection, (item) => {
if (args) {
accumulator = item;
args = false;
} else {
accumulator = func(accumulator, item);
}
})
return accumulator;
};
function each(collection, iterator) {
if (Array.isArray(collection)) {
for (var i = 0; i < collection.length; i++) {
iterator(collection[i], i, collection);
}
} else {
for (var key in collection) {
iterator(collection[key], key, collection);
}
}
};
var numbers = [1, 2, 3]
var sum = reduceTwo(numbers, function(total, number) {
return total + number;
}, 0); // should be 6
console.log(sum)
EDIT: 1st function does not work on objects so rewrote it and now it works with objects.
var numbers = {a: 1, b: 2, c:3};
var sum = reduce(numbers, function(total, number){
return total + number;
});
function reduce (collection, func, accumulator) {
var i = 0;
var isCollection = Array.isArray(collection);
var keys = Object.keys(collection);
var length = isCollection ? collection.length : keys.length;
if (arguments.length < 3) {
isCollection ? accumulator = collection[0] : accumulator = collection[keys[0]];
i++;
}
for (; i < length; i++) {
isCollection ? accumulator = func(accumulator, collection[i]) : accumulator = func(accumulator, collection[keys[i]]);
}
return accumulator;
};
console.log(sum);
So I am working on re-writing the underlying code for some Underscore.js functions.Ok, but why? Just curious \$\endgroup\$