Skip to content

Instantly share code, notes, and snippets.

@boogie666
Last active May 15, 2019 10:17
Show Gist options
  • Save boogie666/d41c20fc07d1dc0879fb1684e8498a09 to your computer and use it in GitHub Desktop.
Save boogie666/d41c20fc07d1dc0879fb1684e8498a09 to your computer and use it in GitHub Desktop.
Full code example
//define the finite state machine data structure...
let fsm = {
"checkLogin" : {"valid" : "login",
"invalid" : "showError"}
};
//create the handler functions...
function checkLogin(state){
if(state.data.username == "admin"){
return {
...state,
transitionTo: "valid"
};
}else {
return {
...state,
transitionTo: "invalid"
};
}
}
function showLogin(state){
return {
data : {
...state.data,
message: "Logged in as " + state.data.username,
},
transitionTo: "done"
};
}
function showError(state){
return {
data : {
...state.data,
message: "Username " + state.data.username + " is invalid"
},
transitionTo: "done"
};
}
//create a mapping between state names and state functions
let fsmRunner = {
"checkLogin": checkLogin,
"showLogin" : showLogin,
"showError" : showError
};
//create the runner
function run(fsm, stateRunner, state){
let currentStateFn = stateRunner[state.currentState];
return Promise.resolve(currentStateFn(state)).then(function(transition){
if(transition.transitionTo === "done"){
return transition.data;
}
return run(fsm, stateRunner, {
...transition,
currentState: fsm[state.currentState][transition.transitionTo]
});
});
}
function runLogin(initialData){
return run(fsm, fsmRunner, {
data : initialData,
currentState: "checkLogin"
});
}
runLogin({"username": "admin"}).then(function(state){
console.log(state.message);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment