Files
30-seconds-of-code/snippets/fibonacci-array-generator.md
Elder Henrique Souza aab7a8da22 Update fibonacci-array-generator.md
The fibonacci sequence being zero indexed as well as the arrays, I think we could just initialize an array with the passed length, fill it with zeroes and use the indexes for the first positions.
2017-12-12 14:45:24 -02:00

17 lines
448 B
Markdown

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