Skip to content

Instantly share code, notes, and snippets.

@amoilanen
Created April 4, 2017 14:13
Show Gist options
  • Save amoilanen/738d661f1a91ec25230a410f01362642 to your computer and use it in GitHub Desktop.
Save amoilanen/738d661f1a91ec25230a410f01362642 to your computer and use it in GitHub Desktop.
Simple demo of generators in JavaScript
function print(obj) {
console.log(JSON.stringify(obj, null));
}
function* gen() {
var x = yield 'a';
var y = yield 'b';
var z = yield 'c';
return [x, y, z];
}
var iter = gen();
print(iter.next('d')); //{"value":"a","done":false}
print(iter.next('e')); //{"value":"b","done":false}
print(iter.next('f')); //{"value":"c","done":false}
print(iter.next('g')); //{"value":["e","f","g"],"done":true}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment