Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Eloquent Javascript's Reduce function

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;
}
like image 655
KMcA Avatar asked Nov 02 '12 21:11

KMcA


People also ask

How does the reduce function work?

The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

How does reduce in JavaScript work?

The reduce() method executes a reducer function for array element. The reduce() method returns a single value: the function's accumulated result. The reduce() method does not execute the function for empty array elements. The reduce() method does not change the original array.

What is accumulator in reduce?

accumulator is the value returned from the previous iteration. It will be initialValue for the first iteration. currentValue is array item in the current iteration.

How should the initial value of accumulator be provided in the reduce function?

If initialValue is provided in the call to reduce , then accumulator will be equal to initialValue and currentValue will be equal to the first value in the typed array. If no initialValue was provided, then accumulator will be equal to the first value in the typed array and currentValue will be equal to the second.


2 Answers

Looking at the code, there is only one possible answer: Since you the function counter is only referenced once when passed to reduce(), 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 the counter() function above.

                   return value of reduce()
                   /
                 etc ...
                /
            counter
           /       \
       counter      xs[2]
      /       \
  counter      xs[1]
 /       \
0         xs[0]

counter() is initially provided with 0 (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 0 is 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 by counter(0, xs[0]) to the reduce() function. As long as elements are left, it then passes this value as new pending total to the counter() 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

function reduce(combine, base, array) {
 forEach(array, function (element) {
    base = combine(base, element);
  });
  return base;
}

As can be seen in the illustration, 0 is passed through base to the function initially, along with element, which denotes xs[0] on the first "iteration" within the forEach construct. The resulting value is then written back to base.

As you can see in the visualization, 0 is the left parameter to the function counter(), whose result is then passed as left parameter to counter(). Since base/total acts as the left paramter within the forEach construct, it makes sense to write that value back to base/total, so the previous result will be passed to counter()/combine() again upon the next iteration. The path of /s is the "flow" of base/total.

Where element comes from

From chapter 6 of Eloquent JavaScript, here is the implementation of forEach() (In the comment, I have substituted the call to action with the eventual values.)

function forEach(array, action) {
  for (var i = 0; i < array.length; i++)
    action(array[i]); // <-- READ AS: base = counter(base, array[i]);
}

action denotes a function, that is called within a simple for loop for every element, while iterating over array.

In your case, this is passed as action to forEach():

function (element) {
    base = combine(base, element);
}

It is the anonymous function defined upon each call to reduce(). So element is "really" array[i] once for each iteration of the for.

like image 33
phant0m Avatar answered Sep 27 '22 22:09

phant0m


the function counter is passed as the first parameter of reduce when called in your first block of code. Within the reduce function, the first parameter is known as combine. This is then called with parameters base and element which are the mysterious arguments you are seeking!

So the tricky bit, is that the function is not executed where it is defined and named, but passed as a parameter to the reduce function, which then executes it.

Edit: elaboration

logic flow

so... the function is defined and named (at point 1), then the definition is passed, without the name to another function (at point 2) along with variables (I called i and ii) where it picks up the name of the first parameter (at point 3) before being called (at point 4) along with the other parameters

edit: further elaboration

I updated the image, to better explain the elements coming from the array.

So i is easier to follow, being created as 0 when the reduce function is called, and allocated the name base as a parameter, before being reassigned as the result of the counter/combine function, which returns the base with a possible increment.

ii starts life as an array passed to countZeroes, and is then passed along the chain until it is iterated over by a forEach loop, which extracts a single element and operates the combine function on it (along with base).

like image 104
Billy Moon Avatar answered Sep 27 '22 22:09

Billy Moon