Created
March 12, 2017 18:49
-
-
Save mightyguava/d7c770e9fd37fb45e6e4709b6ebefb0e to your computer and use it in GitHub Desktop.
Demystifying Async Programming in Javascript - Generator internals counts state machine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?