Files
30-seconds-of-code/snippets/fibonacci.md
Stefan Feješ f559030eac fix naming
2017-12-17 15:41:31 +01:00

403 B

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.

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]