I want to create a function (reduce) that does the following:
Where:
var collection = [1, 2, 3];
and
function iterator(
This is how I would implement it:
alert(reduce([1,2,3], add, 3)); // 9
alert(reduce([1,2,3], add)); // 6
function add(a, b) {
return a + b;
}
function reduce(array, iterator, initial) {
var length = array.length;
var index = 0;
if (arguments.length < 3) {
if (length > 0) var result = array[index++]; // Note 1
else throw new Error("Reduce of empty array with no initial value");
} else var result = initial;
while (index < length) result = iterator(result, array[index++]);
return result;
}
The code is pretty self explanatory. Nevertheless, here's how it works, if the number of arguments passed are less than 3 it means that initial
was not given. Hence we set result
to array[0]
and increment index
. If array
is empty then we throw an error instead. Otherwise we set the result
to the initial
value passed to the function. Everything else works as normal.
Note 1: The reason we don't modify initial
(i.e. write initial = array[index++]
) is because if we use arguments
in a function and also modify the parameters of the function then the function will not be optimized in V8. Hence, it will execute slower.
Hope this helps.