Generating Fibonacci Sequence using ES6 generator functions

Technology CommunityCategory: Fibonacci SequenceGenerating Fibonacci Sequence using ES6 generator functions
VietMX Staff asked 3 years ago

ES6 introduced a new way of working with functions and iterators in the form of Generators (or generator functions). A generator is a function that can stop midway and then continue from where it stopped. In short, a generator appears to be a function but it behaves like an iterator.

For example:

function * iterableObj() {
  yield 'This';
  yield 'is';
  yield 'iterable.'
}
for (const val of iterableObj()) {
  console.log(val);
}
// This
// is 
// iterable.
Implementation
// Iterative Solution for Fibonacci Numbers
function *fibonacci(n) {
  const infinite = !n && n !== 0;
  let current = 0;
  let next = 1;

  while (infinite || n--) {
    yield current;
    [current, next] = [next, current + next];
  }
}

// Recursive Solution for Fibonacci Numbers
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);
}