@nathamanath/state-machine
v1.0.3
Published
A TypeScript finite state machine library
Downloads
42
Maintainers
Readme
@nathamanath/state-machine
A TypeScript finite state machine library.
- Home: https://nathamanath.gitlab.io/state-machine/
- Documentation: https://nathamanath.gitlab.io/state-machine/
- Repo: https://gitlab.com/nathamanath/state-machine
- Issues: https://gitlab.com/nathamanath/state-machine/-/issues
- NPM: https://www.npmjs.com/package/@nathamanath/state-machine
Installation
yarn add @nathamanath/state-machinenpm install @nathamanath/state-machineUsage
State machine has many states, each state has transitions and actions. Transitions declare which states you can change to from current state, actions initiate transitions.
Here we have an on/off switch example. Its too basic to actually be practical on its own, but does show usage.
See /examples, and /tests for more.
import {
StateMachine,
State,
Action,
Transition
} from '@nathamanath/state-machine'
const stateMachine = new StateMachine({
initialState: 'off',
states: [
new State({
name: 'off',
actions: [
new Action({
name: 'toggle',
callback: (m) => {
m.transition('on')
}
})
],
transitions: [new Transition({ to: 'on' })],
enter: () => {},
leave: () => {}
}),
new State({
name: 'on',
actions: [
new Action({
name: 'toggle',
callback: (m) => {
m.transition('off')
}
})
],
transitions: [new Transition({ to: 'off' })],
enter: () => {},
leave: () => {}
})
]
}).init()
console.log(stateMachine.state!.name) // 'off'
stateMachine.commit('toggle')
console.log(stateMachine.state!.name) // 'on'Author
Nathan Goddard - Initial work
License
This project is licensed under the MIT License - see the LICENSE file for details.
