a tiny javascript state machine that's just a function
MIT License
If I'm hungry and I eat a salad, I get full. If I eat a burrito, I get too full. As time passes, I get hungrier and hungrier.
We can model this with a state diagram if we are huge nerds:
We can then model this in JavaScript:
var myStates = {
hungry: {
eatSalad: 'full',
eatBurrito: 'tooFull',
timePasses: 'hungry'
},
full: {
timePasses: 'hungry'
},
tooFull: {
timePasses: 'full'
}
}
Now we can transition between them!
// returns "hungry"
functionalStateMachine({
states: myStates,
initial: 'full',
apply: ['timePasses']
})
// returns "hungry"
functionalStateMachine({
states: myStates,
initial: 'full',
apply: ['timePasses', 'timePasses']
})
// returns "tooFull"
functionalStateMachine({
states: myStates,
initial: 'hungry',
apply: ['eatBurrito']
})
// returns "full"
functionalStateMachine({
states: myStates,
initial: 'hungry',
apply: ['eatBurrito', 'timePasses']
})
To use this with Node, Browserify, or Webpack:
var functionalStateMachine = require('@evanhahn/functional-state-machine');
functionalStateMachine({
states: myStates,
initial: 'full',
apply: ['timePasses']
})
To use in the browser:
<script src="functionalstatemachine.js"></script>
<script>
functionalStateMachine({
states: myStates,
initial: 'hungry',
apply: ['eatBurrito']
})
</script>
Enjoy!