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 mightyguava/d7c770e9fd37fb45e6e4709b6ebefb0e to your computer and use it in GitHub Desktop.
Save mightyguava/d7c770e9fd37fb45e6e4709b6ebefb0e to your computer and use it in GitHub Desktop.
Demystifying Async Programming in Javascript - Generator internals counts state machine
function counts(start) {
let state = 0;
let done = false;
function go() {
let result;
switch (state) {
case 0:
result = start + 1;
state = 1;
break;
case 1:
result = start + 2;
state = 2;
break;
case 2:
result = start + 3;
state = 3;
break;
case 3:
result = start + 4;
done = true;
state = -1;
break;
default:
break;
}
return {done: done, value: result};
}
return {
next: go
}
}
const counter = counts(0);
console.log(counter.next()); // {value: 1, done: false}
console.log(counter.next()); // {value: 2, done: false}
console.log(counter.next()); // {value: 3, done: false}
console.log(counter.next()); // {value: 4, done: true}
console.log(counter.next()); // {value: undefined, done: true}
@russfrisch
Copy link

I'm currently reading through the blog where this code snippet is presented and just have a quick question: Given that this is an example of how to build a generator using ES5, shouldn't the the lets be vars?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment