Skip to content

Instantly share code, notes, and snippets.

@digitalhitler
Created October 31, 2016 22:10
Show Gist options
  • Save digitalhitler/4203026aa2ad71653a00d0f72b00709d to your computer and use it in GitHub Desktop.
Save digitalhitler/4203026aa2ad71653a00d0f72b00709d to your computer and use it in GitHub Desktop.
JS Generators Explained Template
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