Fibonacci generator using EcmaScript 6 (es6)

I took my first stab at the --harmony flag on node 11 to play with generators.

Thanks to this video:

Here’s a simple example of using an ES6 generator to generate the first 10 numbers in the Fibonnaci sequence:

What wasn’t clear to me before watching this video by Netflix UI Architect Jafar Husain was that a generator returns an “iterator”….and on that iterator you call “.next()” to get the next yield. A generator can yield infinite times, so in this case we loop over the call 10 times to get the first 10 numbers.

An iterator will return an object that has the value, and a done flag that tells you whether the generator is finished. { value: 0, done: false }.

Then when you call you will get this response object: { value: 1, done: false }. In this example, the generator goes on forever, so it would never produce done: true.

Here is a link to the gist:

  • 112864

    you can do [val1, val2] = [val2, val1]