Update accumulate

This commit is contained in:
Isabelle Viktoria Maciohsek
2022-01-30 13:19:09 +02:00
parent 27bdc4676a
commit 28a8bb287d

View File

@ -2,17 +2,18 @@
title: accumulate
tags: math,array,intermediate
firstSeen: 2020-05-04T12:20:46+03:00
lastUpdated: 2020-11-03T21:46:13+02:00
lastUpdated: 2022-01-30T13:10:13+02:00
---
Creates an array of partial sums.
- Use `Array.prototype.reduce()`, initialized with an empty array accumulator to iterate over `nums`.
- Use `Array.prototype.slice(-1)`, the spread operator (`...`) and the unary `+` operator to add each value to the accumulator array containing the previous sums.
- Use `Array.prototype.slice()` to get the previous partial sum or `0` and add the current element to it.
- Use the spread operator (`...`) to add the new partial sum to the accumulator array containing the previous sums.
```js
const accumulate = (...nums) =>
nums.reduce((acc, n) => [...acc, n + +acc.slice(-1)], []);
nums.reduce((acc, n) => [...acc, n + (acc.slice(-1)[0] || 0)], []);
```
```js