-
-
Save getify/83e1f7072cae4d60bfbe to your computer and use it in GitHub Desktop.
sync state machines with ES6 generators
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
// 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."); | |
} | |
} | |
}; | |
} |
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
// 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."); | |
} | |
} |
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
var m = stateMachine(); | |
m.next(); // state 1! | |
m.next(); // state 2! | |
m.next(); // state 3! | |
m.next(); // already done. | |
m.next(); // already done. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is there a way to serialize the generator and restore its state?