Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khanghoang/86da26787ce4815dc47459c9308c870d to your computer and use it in GitHub Desktop.
Save khanghoang/86da26787ce4815dc47459c9308c870d to your computer and use it in GitHub Desktop.
Some thoughts about Generators

Generators

The playground:

  • I've created a jsbin for you to play with Generators. In the practical project, you need to have either facebook-regenerator or babel-polyfill to run it.
    The playground

What is generator:

  • Generator's interface
interface Generator extends Iterator {
   next(value?: any): IteratorResult;
   throw(exception: any);
}
  • It's object after all [suprise]

Generator's gotchas:

  • Generator has implicit return undefined.
  • Throw and return are equal.

How to create generators:

  • Via function declaration:
function* generatorFunction() { ... }
  • Via function expression:
const generatorFunction = function* () { ... }
  • Via object literal
const objectA = {
    * generatorFunc() { ... }
}

Via a generator method definition in a class definition (which can be a class declaration or a class expression):

class Foo {
    * generatorMethod() {
        ...
    }
}

const foo = new Foo();
let genObj = foo.generatorMethod();

How do we use Generator in real life?

Iterators (data producers): Each yield can return a value via next(), which means that generators can produce sequences of values via loops and recursion. Due to generator objects implementing the interface Iterable [5], these sequences can be processed by any ECMAScript 6 construct that supports iterables. Two examples are: for-of loops and the spread operator (...) javascript class BinaryTree { constructor(value, left=null, right=null) { this.value = value; this.left = left; this.right = right; }

/** Prefix iteration */
* [Symbol.iterator]() {
    yield this.value;
    if (this.left) {
        yield* this.left;
    }
    if (this.right) {
        yield* this.right;
    }
}

}

### Preferences
- ES6 generators in depth - http://www.2ality.com/2015/03/es6-generators.html
- ES6 features - https://github.com/lukehoban/es6features#generators
- TC39 proposal async interation - https://github.com/tc39/proposal-async-iteration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment