Skip to content

Instantly share code, notes, and snippets.

@halferty
Created June 9, 2017 20:42
Show Gist options
  • Save halferty/f3f93baaea9d379b3c77b4044064c4ac to your computer and use it in GitHub Desktop.
Save halferty/f3f93baaea9d379b3c77b4044064c4ac to your computer and use it in GitHub Desktop.
JS Generators example
function* exampleGenerator(i) {
yield i + 1;
yield i + 2;
yield i + 3;
}
function run(iter) {
let done = false;
while (!done) {
({ value, done } = iter.next());
if (!done) {
console.log(value);
}
}
}
run(exampleGenerator(2));
/*----------------------*/
function* exampleGenerator2(m) {
while (true) {
const n = yield;
console.log(n + m);
}
}
function run2(iter) {
iter.next(); // Run the generator until the first `yield` statement
iter.next(1);
iter.next(2);
iter.next(3);
iter.return();
}
run2(exampleGenerator2(2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment