Skip to content

Instantly share code, notes, and snippets.

@silesky
Last active October 10, 2017 18:10
Show Gist options
  • Save silesky/e1b77e86d032c71c291732a303658599 to your computer and use it in GitHub Desktop.
Save silesky/e1b77e86d032c71c291732a303658599 to your computer and use it in GitHub Desktop.
blog_generator.js
function* gen() { // new * syntax for declaring generator functions.
yield 1 // yield says 'output the value and stop'.
yield 2
}
// we use our generator to create an 'iterator': an object with a .next method.
const myIterator = gen()
// every time .next gets called, it returns an object that looks like: {value: ..., done: ...}
myIterator.next() //=> {value: 1, done: false}
myIterator.next() //=> {value: 2, done: false}
myIterator.next() //=> {value: 3, done: true}
// AND you can also pass stuff into it.
function* gen() {
const x = 1 + (yield ‘PAUSED!’);
yield x
}
myIterator.next().value //=> PAUSED!
myIterator.next(2).value //=> 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment