0.1.0 • Published 9 years ago

@evanhahn/functional-state-machine v0.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
9 years ago

functional finite state machine for the javascript

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:

a state diagram

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!