/typescript-state-machine

strongly typed typescript finite state machine. (inspired by javascript-state-machine)

Primary LanguageTypeScriptMIT LicenseMIT

Typescript State Machine

A strongly typed library for finite state machines.

matter state machine

Installation

npm install fsm-typescript --save-dev

Usage

A state machine can be constructed using:

const fsm = new StateMachine({
  init: 'solid',
  transitions: [
    { name: 'melt', from: 'solid', to: 'liquid' },
    { name: 'freeze', from: 'liquid', to: 'solid' },
    { name: 'vaporize', from: 'liquid', to: 'gas' },
    { name: 'condense', from: 'gas', to: 'liquid' },
  ],
  lifecycles: {
    onMelt: function () {
      console.log('I melted')
    },
    onFreeze: function () {
      console.log('I froze')
    },
    onVaporize: function () {
      console.log('I vaporized')
    },
    onCondense: function () {
      console.log('I condensed')
    },
  },
})

... which creates an object with a current state property:

  • fsm.state

... methods to transition to a different state:

  • fsm.melt()
  • fsm.freeze()
  • fsm.vaporize()
  • fsm.condense()

... observer methods called automatically during the lifecycle of a transition:

  • onMelt()
  • onFreeze()
  • onVaporize()
  • onCondense()

... along with the following helper methods:

  • fsm.can(t) - return true if transition t can occur from the current state
  • fsm.cannot(t) - return true if transition t cannot occur from the current state
  • fsm.transitions() - return list of transitions that are allowed from the current state
  • fsm.allTransitions() - return list of all possible transitions
  • fsm.allStates() - return list of all possible states

Terminology

A state machine consists of a set of States

  • solid
  • liquid
  • gas

A state machine changes state by using Transitions

  • melt
  • freeze
  • vaporize
  • condense

A state machine can perform actions during a transition by observing Lifecycle Events

  • onBeforeMelt
  • onAfterMelt
  • onLeaveSolid
  • onEnterLiquid
  • ...

A state machine can also have arbitrary Data.

Documentation

Read more about

License

See MIT LICENSE file.