Files
30-seconds-of-code/snippets/fibonacci-array-generator.md
2017-12-12 19:20:56 +02:00

11 lines
403 B
Markdown

### Fibonacci array generator
Create an empty array of the specific length, initializing the first two values (`0` and `1`).
Use `Array.reduce()` to add values into the array, using the sum of the last two values, except for the first two.
```js
const fibonacci = n =>
Array(n).fill(0).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),[]);
// fibonacci(5) -> [0,1,1,2,3]
```