Understanding Eloquent Javascript's Reduce function

前端 未结 3 1488
长发绾君心
长发绾君心 2020-12-29 18:00

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 amo

相关标签:
3条回答
  • 2020-12-29 18:02

    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.

    0 讨论(0)
  • 2020-12-29 18:27

    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).

    0 讨论(0)
  • 2020-12-29 18:27

    The reduce method passes the parameters in. Somewhere in the source code of the reduce function is probably something like this:

    function reduce(iterator, memo, collection) { // in your example, iterator here is your counter function
        …
        // while looping through the collection you passed in
        memo = iterator(memo, collection[i], i); // it calls your counter function and
                                                 // passes the total and the current array
                                                 // element as well as the current index,
                                                 // then stores the result to be passed in
                                                 // with the next array element
        …
        return memo;
    }
    

    Addendum

    Maybe this will help illustrate better (jsfiddle):

    // very simple reduce implementation
    function reduce(iterator, memo, collection) {
        for (var i = 0; i < collection.length; i++) {
            memo = iterator(memo, collection[i], i);
        }
        return memo;
    }
    
    zeroes = [1,0,0,1,1,0,1];
    function counter(total, element) { return total + (element === 0 ? 1 : 0); }
    
    alert(reduce(counter, 0, zeroes));
    
    0 讨论(0)
提交回复
热议问题