Last active
May 15, 2019 10:17
-
-
Save boogie666/d41c20fc07d1dc0879fb1684e8498a09 to your computer and use it in GitHub Desktop.
Full code example
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
//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