Created
October 31, 2016 22:10
-
-
Save digitalhitler/4203026aa2ad71653a00d0f72b00709d to your computer and use it in GitHub Desktop.
JS Generators Explained Template
This file contains hidden or 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 interpreter(program) { | |
// takes in `cmd` — which is the value that was `yielded` | |
// and does something — UP TO YOU. | |
// it is important that it calls callback when done. | |
// optionally, it can communicate some value back to | |
// the program by passing it to the callback | |
function interpretCommand(cmd, callback) { | |
callback(); | |
} | |
const iterator = program(); | |
// run the program | |
let next = iterator.next(); | |
// get the first command | |
// as long as there is the next command | |
while (!next.done) { | |
const cmd = next.value; | |
// interpret it | |
interpretCommand(cmd, function(value) { | |
// then get the next command | |
next = iterator.next(value) | |
}); | |
} // program ended | |
} | |
// use as: | |
interpreter(function* program() { | |
yield someCommand; | |
}); | |
// Understanding JavaScript generators cheatsheet⚠Fill in the `interpretCommand` function. | |
// It takes a command and should call the callback when needed |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment