https://github.com/ggoodman/fsm
Fully typed finite state machine for JavaScript and TypeScript.
https://github.com/ggoodman/fsm
Last synced: 3 months ago
JSON representation
Fully typed finite state machine for JavaScript and TypeScript.
- Host: GitHub
- URL: https://github.com/ggoodman/fsm
- Owner: ggoodman
- License: mit
- Created: 2020-08-28T17:27:16.000Z (over 5 years ago)
- Default Branch: main
- Last Pushed: 2021-03-25T20:55:03.000Z (almost 5 years ago)
- Last Synced: 2025-04-19T05:47:42.427Z (9 months ago)
- Language: TypeScript
- Size: 24.4 KB
- Stars: 48
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
- awesome-list - fsm
README
# @ggoodman/fsm
> Fully typed finite state machine for JavaScript and TypeScript
## Installation
```bash
npm install @ggoodman/fsm
```
## Example
The example below demonstrates a traffic light that cycles eternally on a timer.
> **Note**: Instead of defining the 'tick' event, we could have called `ctx.transitionTo('red' | 'green' | 'yellow')` directly.
```typescript
import { DefineEvent, DefineState, Service } from '@ggoodman/fsm';
type Red = DefineState<'red'>;
type Yellow = DefineState<'yellow'>;
type Green = DefineState<'green'>;
type Tick = DefineEvent<'tick'>;
const service = Service.define(
(s) =>
s
.defineState('red', (red) =>
red
.onEnter((ctx) => ctx.runAfter(30 * 1000, (ctx) => ctx.send('tick')))
.onEvent('tick', (ctx) => ctx.transitionTo('green'))
)
.defineState('green', (red) =>
red
.onEnter((ctx) => ctx.runAfter(60 * 1000, (ctx) => ctx.send('tick')))
.onEvent('tick', (ctx) => ctx.transitionTo('yellow'))
)
.defineState('yellow', (red) =>
red
.onEnter((ctx) => ctx.runAfter(10 * 1000, (ctx) => ctx.send('tick')))
.onEvent('tick', (ctx) => ctx.transitionTo('red'))
),
'red'
);
service.onStateChange((state) => {
console.log('State changed to %s', state.id);
});
service.start();
// State changed to red
// State changed to green
// State changed to yellow
// ...
```