liveBook · Manning

Accumulator

As explained in Grokking Simplicity

A function passed to a reduction operation that combines the accumulated result with the current sequence element.

An accumulator is the running result in a reduction. Its function receives the current accumulator and the current array element, then returns the next accumulator value. section 12.11

function reduce(array, init, f) { #1
    var accum = init; #2
    forEach(array, function(element) {
        accum = f(accum, element); #3
    });
    return accum; #4
}

Follow the reduction loop: initialize the accumulator, update it for each element, and return the final value. section 12.11

Counting purchases

A purchase counter starts at 0. For each customer, the accumulator function adds that customer’s purchase count: reduce(customers, 0, function(total, customer) { return total + customer.purchase.length; }). section 12.11

Choose the initial value to match the operation:

  • Use 0 for addition and an empty string for string concatenation. section 12.12
  • Use 1 for multiplication; reduction over an empty array returns the initial value. section 12.12

How Grokking Simplicity covers it

How deep it goes
Defines the two arguments, return rule, initialization, and iteration behavior, but does not descend into implementation internals beyond a loop.
Examples
Uses purchase counting, string concatenation, numeric sum and product, and minimum or maximum exercises.
What it assumes
Assumes arrays and functions, while teaching reduction and accumulator behavior through concrete JavaScript examples.
What you can do after
Apply it via reduce to build accumulation functions with appropriate initial values.
How it connects
Connects reduce with map, filter, initial values, empty arrays, and functional iteration.

Also explained in

Compare how 4 books explain accumulator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Simplicity. The section links point to the parts of the book it draws on.