From b3e2b52991304027a5a17f28a2c64401187911fd Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Mon, 4 May 2020 12:20:46 +0300 Subject: [PATCH] Add accumulate --- snippets/accumulate.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 snippets/accumulate.md diff --git a/snippets/accumulate.md b/snippets/accumulate.md new file mode 100644 index 000000000..08f061829 --- /dev/null +++ b/snippets/accumulate.md @@ -0,0 +1,17 @@ +--- +title: accumulate +tags: math,array,beginner +--- + +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. + +```js +const accumulate = (...nums) => nums.reduce((acc, n) => [...acc, n + +acc.slice(-1)],[]); +``` + +```js +accumulate(1, 2, 3, 4); // [1, 3, 6, 10] +accumulate(...[1, 2, 3, 4]); // [1, 3, 6, 10] +```