Files
30-seconds-of-code/snippets/fibonacci.md
2017-12-22 13:47:32 +08:00

13 lines
474 B
Markdown

### fibonacci
Generates an array, containing the Fibonacci sequence, up until the nth term.
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.from({ length: n}).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []);
// fibonacci(5) -> [0,1,1,2,3]
```