## Generate Fibonacci series using generators

·   ·  ☕ 2 min read

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 -

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18  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).

Stay in touch!
Share on

WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things