I am working through Eloquent Javascript. The function count takes an array and a test function (equals(x)) as arguments, and returns the amount of elements in the array for which the test function returned true.
I understand the broad way that these functions are working, and that logically the total argument to the anonymous function passed to reduce has a value of zero.
Can someone help me to see where the value for total is coming from specifically though? I want to have a clearer picture in my mind.
function count(test, array) {
return reduce(function(total, element) { // Where is the value for total coming from?
return total + (test(element) ? 1 : 0);
}, 0, array);
}
function equals(x) {
return function(element) {return x === element;};
}
function countZeroes(array) {
return count(equals(0), array);
}
Reduce Function from earlier:
function reduce(combine, base, array) {
forEach(array, function (element) {
base = combine(base, element);
});
return base;
}
forEach Function from earlier:
function forEach(array, action) {
for (var i = 0; i < array.length; i++)
action(array[i]);
}
The 3 arguments you passed to reduce were:
The function then takes
baseand passes it to thecombinefunction as thetotalargument:Basically, what is happening here is that for each element in the array you just passed (as the 3rd argument
array) the function takes the argumentbaseand increments it using the anonymous function you have provided (which first checks if the element passestest). Finally, after it has iterated over all the elements, it returns the final value ofbase.Perhaps this will help explain:
Let us look at the function invocation and definition closely:
The values of each of
anon,0, andtestarray, get passed into the function. Within the function, their values can be accessed by the parameter names in the function definition.