Files
30-seconds-of-code/snippets/fibonacci-array-generator.md
Angelos Chalaris 43f8529cb9 Added samples
2017-12-12 17:50:08 +02:00

454 B

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.

const fibonacci = n =>
  Array.apply(null, [0,1].concat(Array(n-2))).reduce(
    (acc, val, i) => {
      acc.push( i>1 ? acc[i-1]+acc[i-2] : val);
      return acc;
    },[]);
// fibonacci(5) -> [0,1,1,2,3]