November 2017
Intermediate to advanced
386 pages
9h 22m
English
Programming .reduce() is, from the outset, a bit trickier, since you can decide to omit the initial value for the accumulator. Since we mentioned earlier that providing that value is generally better, let's work here under the assumption that it will be given; dealing with the other possibility wouldn't be too hard.
The base case is simple: if the array is empty, the result is the accumulator. Otherwise, we must apply the reduce function to the current element and the accumulator, update the latter, and then continue working with the rest of the array. This can be a bit confusing because of the ternary operators, but after all, we've seen, it should be clear enough:
const reduceR = (orig, cb, accum) => { const ...