Skip to content

Instantly share code, notes, and snippets.

@getify
Created September 8, 2015 13:47
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save getify/83e1f7072cae4d60bfbe to your computer and use it in GitHub Desktop.
Save getify/83e1f7072cae4d60bfbe to your computer and use it in GitHub Desktop.
sync state machines with ES6 generators
// normal JS function
function stateMachine() {
var state = 1;
return {
next: function() {
switch (state) {
case 1:
// handle state 1
console.log("state " + state + "!");
state = 2; // transition to next state
break;
case 2:
// handle state 2
console.log("state " + state + "!");
state = 3; // transition to next state
break;
case 3:
// handle state 3
console.log("state " + state + "!");
state = 0; // transition to next state
break;
default:
// handle state 0
console.log("already done.");
}
}
};
}
// ES6 generator
function *stateMachine() {
// handle state 1
var state = 1;
console.log("state " + state + "!");
state = 2; // transition to next state
yield;
// handle state 2
console.log("state " + state + "!");
state = 3; // transition to next state
yield;
// handle state 3
console.log("state " + state + "!");
state = 0; // transition to next state
// handle state 0
while (true) {
yield;
console.log("already done.");
}
}
var m = stateMachine();
m.next(); // state 1!
m.next(); // state 2!
m.next(); // state 3!
m.next(); // already done.
m.next(); // already done.
@kechkibet
Copy link

Is there a way to serialize the generator and restore its state?

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