Skip to content

Instantly share code, notes, and snippets.

@mechanicles
Last active August 29, 2015 14:22
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 mechanicles/d58818713e55fd4b1bc0 to your computer and use it in GitHub Desktop.
Save mechanicles/d58818713e55fd4b1bc0 to your computer and use it in GitHub Desktop.
JavaScript ES6: Simple Generator Example.
// Example 1
function* numbers(){
var n = 1;
var a;
while(true) {
a = yield n++;
console.log('a:', a);
}
};
var gen = numbers();
console.log(gen.next());
console.log(gen.next(2));
console.log(gen.next(5));
// Output:
// {"value":1,"done":false}
// a: 2
// {"value":2,"done":false}
// a: 5
// {"value":3,"done":false}
// Example 2
function* numbers(){
var n = 1;
var a;
while(true) {
yield n++;
}
};
for (var n of numbers()) {
if (n > 50) break;
console.log(n);
}
// output:
// 1
// 2
// 3
// .
// .
// 50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment