fsm-base

0.8.0 • Public • Published

view on npm npm module downloads Gihub repo dependents Gihub package dependents Node.js CI js-standard-style

fsm-base

Finite state machine.

Either mix it into an existing object:

import StateMachine from 'fsm-base'

const exampleClient = {}

StateMachine.mixInto(exampleClient, 'offline', [
  { from: 'offline', to: 'connecting' },
  { from: 'connecting', to: 'online' },
  { from: ['connecting', 'online'], to: 'offline' }
])

exampleClient._onStateChange = function (state, prevState) {
  console.log(`Moved to ${state} from ${prevState}`)
}

console.log(exampleClient.state) // Prints 'offline' - the defined initial state
exampleClient.state = 'connecting' // valid move
exampleClient.state = 'online' // valid move
exampleClient.state = 'offline' // valid move
exampleClient.state = 'something unspecified' // invalid move, throws an exception.

..or define a class which extends it:

class AnotherClient extends StateMachine {}

const anotherClient = new AnotherClient()
anotherClient._initStateMachine('offline', [
  { from: 'offline', to: 'connecting' },
  { from: 'connecting', to: 'online' },
  { from: ['connecting', 'online'], to: 'offline' }
])

anotherClient.state = 'connecting'
// etc

fsm-base

StateMachine

Kind: Exported class

stateMachine.state : string

The current state

Kind: instance property of StateMachine
Throws:

  • INVALID_MOVE if an invalid move made

stateMachine._initStateMachine(initialState, validMoves)

Kind: instance method of StateMachine

Param Type Description
initialState string Initial state, e.g. 'pending'.
validMoves Array.<object> Array of valid move rules.

stateMachine._onStateChange(state, prevState)

Invoked on every state change

Kind: instance method of StateMachine

Param Type Description
state string the new state
prevState string the previous state

stateMachine.resetState()

Reset to initial state.

Kind: instance method of StateMachine

StateMachine.mixInto(target, initialState, validMoves)

Kind: static method of StateMachine

Param Type Description
target object The target to receive the state machine behaviour.
initialState string Initial state, e.g. 'pending'.
validMoves Array.<object> Array of valid move rules.

© 2015-23 Lloyd Brookes <75pound@gmail.com>. Documented by jsdoc-to-markdown.

Package Sidebar

Install

npm i fsm-base

Weekly Downloads

84

Version

0.8.0

License

MIT

Unpacked Size

20 kB

Total Files

7

Last publish

Collaborators

  • 75lb