Tiny dependency-free state-machine implementation in javascript.
npm install @desicochrane/machine
- Define a new state machine specification
import Machine, { Transition } from '@desicochrane/machine' const spec = { __start__: 'off', off: { click: Transition('on'), }, on: { click: Transition('off'), } }
- Instantiate your machine with data:
const m = Machine(spec)
- Use the machine
console.log(m.state) // "off" m.click() console.log(m.state) // "on"
- Export to Dot file:
import { Dot } from '@desicochrane/machine' import fs from 'fs' const dot = Dot(spec) fs.writeFileSync('machine.dot', dot);
- Optionally pass in data
import Machine, { Transition } from '@desicochrane/machine' const spec = { __start__: 'off', off: { click: Transition('on', (m, args) => { m.data.count += args }), }, on: { click: Transition('off', (m, args) => { m.data.count -= args }), } } const m = Machine(spec, { count: 0 }) m.click(3) console.log(m.data.count) // 3 m.click(2) console.log(m.data.count) // 1