How to Use Javascript Generators

Tue Feb 27 2018

I have tried to learn generators for quite a while, but for each time that I started, I said to myself:

thats enough, Ill learn when Ill need it

Well not this time! after you really understand the concept of generators you will find the true magic of it, the vast capabilities you could do with that.

Generators are reading and sending data, and can run endlessly.

Lets learn by examples:

function* simpleGenerator() { //the "*" mans its a generator  
    yield 1;
    yield 2;
}
let ge = simpleGenerator();  
console.log(ge.next()); // { value: 1, done: false }  
console.log(ge.next()); // { value: 2, done: false }  
console.log(ge.next()); // { value: undefined, done: true }  

each yield returns a value and stops the function at its place.

When you call next again, your generator will continue from its last stopped point.

When you yields are finished the generator will be marked as done and you can do a simple return if you would like.

Now lets do a quick example with sending data to the yields:

function* simpleGenerator() {  
    let x = yield 5;
    let y = 2 + (yield x);
    return y;
}

let ge = simpleGenerator();  
console.log(ge.next("dontcare")); //{ value: 5, done: false }  
console.log(ge.next(100)); //{ value: 100, done: false }  
console.log(ge.next(1000)); //{ value: 1002, done: true }  

as you can see here we pass items to the yield.

The first yield item we pass is ignored, as always the item we pass will go the the previous yield that was used.

In the last next, we see the generator was finished and got done: true. This is because yield were finished and we got returned the last value.

Now a simple fibonacci sequence in a generator:

function* fibonacciRunner() {  
      let first = 1;
      let second = 1;
    yield first;
     yield second;

      while(true) {
          let result = first + second;
          first = second;
          second = result;
          yield result;
      }
}

var fibonacci = fibonacciRunner();

console.log(fibonacci.next().value); // 1  
console.log(fibonacci.next().value); // 1  
console.log(fibonacci.next().value); // 2  
console.log(fibonacci.next().value); // 3  
console.log(fibonacci.next().value); // 5  
console.log(fibonacci.next().value); // 8  
console.log(fibonacci.next().value); // 13  
console.log(fibonacci.next().value); // 21  
console.log(fibonacci.next().value); // 34  

This generator will run endlessly, as it will never stop yielding the next response.