Generate Fibonacci series using generators

Generate Fibonacci series with generators and feel good about yourself.

Previously you have seen how the totally practical example of generating Fibonacci series was breathing fire with memoization, and may have also come across using loops or recursion to solve the same problem. But, there is no fun in all that - this is real-life and we have to “generate” fun (yep, there we go again).

If you have forgotten your schooling, here’s the series - any number is the sum of previous two numbers (except the first two, of course).

fibo(5) = [1, 1, 2, 3, 5]

The question on everyone’s mind is - can we really do that using generators?

Of course, you can! I would not be wasting your bandwidth, burdening the environment with electricity to power all the servers, and wasting even more electricity for you to read this post if we could not do that.

All the fluff so far just leads to this simple algo -

function* fiboGen(fibo) {
  i = 0;
  j = 1;
  for (;;) {
    [i, j] = [j, i + j];
    yield j;
  }
}

const fibo = fiboGen();
console.log(1);
console.log(fibo.next().value);
console.log(fibo.next().value);
console.log(fibo.next().value);
console.log(fibo.next().value);
console.log(fibo.next().value);

// 1 1 2 3 5 8

The best part - you can go on and on with this logic to establish a world record for longest Fibonacci series. (I was joking - don’t try that at home).

comments powered by Disqus