Skip to main content

accumulate

TS JS Deno

Returns an array of partial sums.

Use Array.prototype.reduce(), Array.prototype.slice(-1) and the unary + operator to add each value to the unary array containing the previous sum.

typescript
const accumulate = (...nums: number[]): number[] =>
nums.reduce((acc: number[], n) => [...acc, n + +acc.slice(-1)], []);
typescript
accumulate(1, 2, 3, 4); // [1, 3, 6, 10]
accumulate(...[1, 2, 3, 4]); // [1, 3, 6, 10]