@evanhahn/functional-state-machine

0.1.0 • Public • Published

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!

Readme

Keywords

Package Sidebar

Install

npm i @evanhahn/functional-state-machine

Weekly Downloads

1

Version

0.1.0

License

MIT

Last publish

Collaborators

  • evanhahn