loicdescotte
6/17/2015 - 12:04 AM

Fibonacci ES6 Generator

Fibonacci ES6 Generator

let [...first10] = fibonacci(10);
console.log(first10);
// [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
function *fibonacci(n = null, current = 0, next = 1) {
  if (n === 0) {
    return current;
  }

  let m = n !== null ? n - 1 : null;

  yield current;
  yield *fibonacci(m, next, current + next);
}
function *fibonacci(n) {
  const infinite = !n && n !== 0;
  let current = 0;
  let next = 1;
  
  while (infinite || n--) {
    yield current;
    [current, next] = [next, current + next];
  }
}