cumulativeSum
is the function value => sum += value
, with sum
initialized to zero. Every time it’s called, sum
is updated and will equal the previous value (output[n-1]) when called the next time (with input[n]).
Note that sum
will need to be set to zero explicitly when you want to reuse the summation. The most convenient way to handle this may be to just inline the code instead of using a named function.
const cumulativeSum = (sum => value => sum += value)(0);
console.log([5, 10, 3, 2].map(cumulativeSum));
Comments