In Eloquent Javascript, the author asks the reader to write a function countZeroes, which takes an array of numbers as its argument and returns the amount of zeroes that occur in it as another example for the use of the reduce function.
I know
- that the concept of the reduce function is to take an array and turn it to a single value.
- what the ternary operator is doing which is the essential portion of the function.
I don’t know
- where the arguments for the counter function are coming from.
From the book:
function countZeroes(array) {
function counter(total, element) { // Where are the parameter values coming from?
return total + (element === 0 ? 1 : 0);
}
return reduce(counter, 0, array);
}
Earlier example from the text:
function reduce(combine, base, array) {
forEach(array, function (element) {
base = combine(base, element);
});
return base;
}
Looking at the code, there is only one possible answer: Since you the function
counteris only referenced once when passed toreduce(), reduce must thus provide the arguments to the function.How reduce works
Here is a visualization of how reduce works. You need to read the diagrom from top to bottom,
/and\denote which parameters (below) are passed to thecounter()function above.counter()is initially provided with0(after all, the initial total amount of seen zeroes when you haven’t processed any elements yet is just zero) and the first element.That
0is increased by one if the first element of the array is a zero. The new total after having seen the first element is then returned bycounter(0, xs[0])to thereduce()function. As long as elements are left, it then passes this value as new pending total to thecounter()function, along with the next element from your array:xs[1].This process is repeated as long as there are elements in the array.
Mapping this concept to the code
As can be seen in the illustration,
0is passed throughbaseto the function initially, along withelement, which denotesxs[0]on the first “iteration” within theforEachconstruct. The resulting value is then written back tobase.As you can see in the visualization,
0is the left parameter to the functioncounter(), whose result is then passed as left parameter tocounter(). Sincebase/totalacts as the left paramter within theforEachconstruct, it makes sense to write that value back tobase/total, so the previous result will be passed tocounter()/combine()again upon the next iteration. The path of/s is the “flow” ofbase/total.Where
elementcomes fromFrom chapter 6 of Eloquent JavaScript, here is the implementation of
forEach()(In the comment, I have substituted the call toactionwith the eventual values.)actiondenotes a function, that is called within a simpleforloop for every element, while iterating overarray.In your case, this is passed as
actiontoforEach():It is the anonymous function defined upon each call to
reduce(). Soelementis “really”array[i]once for each iteration of thefor.