generators 

Send to Kindle
home » snippets » javascript » es6 » generators



Snippets

Counter

function* count(initial) {
  var i = initial;
  while(true) {
    yield i++;
  }
}

var c = count(0);

console.log(c.next().value); // 0
console.log(c.next().value); // 1
console.log(c.next().value); // 2

Chaining Generators

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*#Example_with_yield*

// yield* to yield from another generator
function* anotherGenerator(i) {
  yield i + 1;
  yield i + 2;
  yield i + 3;
}

function* generator(i){
  yield i;
  yield* anotherGenerator(i);
  yield i + 10;
}

var gen = generator(10);

console.log(gen.next().value); // 10
console.log(gen.next().value); // 11
console.log(gen.next().value); // 12
console.log(gen.next().value); // 13
console.log(gen.next().value); // 20