Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/basementuniverse/simple-state-machine
Define finite state machines and validate state transitions
https://github.com/basementuniverse/simple-state-machine
Last synced: 23 days ago
JSON representation
Define finite state machines and validate state transitions
- Host: GitHub
- URL: https://github.com/basementuniverse/simple-state-machine
- Owner: basementuniverse
- License: mit
- Created: 2022-02-18T15:43:45.000Z (almost 3 years ago)
- Default Branch: master
- Last Pushed: 2023-10-25T12:22:26.000Z (about 1 year ago)
- Last Synced: 2024-04-26T04:03:06.820Z (9 months ago)
- Language: TypeScript
- Size: 78.1 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Simple State Machine
Define finite state machines and validate state transitions.
This library doesn't currently provide state-change events or methods for transitioning between states; all it does is provide a format for defining state machines, and a method for checking that a given transition is valid.
## Installation
```
npm install @basementuniverse/simple-state-machine
```## Usage
```typescript
import {
StateMachine,
validateTransition,
} from '@basementuniverse/simple-state-machine';// Define a finite state machine
const myStateMachine: StateMachine = {
open: [
'closedAndUnlocked',
],
closedAndUnlocked: [
'open',
'closedAndLocked',
],
closedAndLocked: [
'closedAndUnlocked',
],
};// Let's validate some transitions...
let result: boolean = false;// Test #1
result = validateTransition(
myStateMachine,
'open',
'closedAndUnlocked'
);// result will be true (this is a valid transition)
console.assert(result);// Test #2
result = validateTransition(
myStateMachine,
'closedAndLocked',
'open'
);// result will be false (this is not a valid transition)
console.assert(!result);// Test #3
result = validateTransition(
myStateMachine,
'open',
'closedAndLocked',
{
throwErrors: true,
}
);
// this will throw an error with the message:
// "Invalid state transition: unable to transition from 'open' to 'closedAndLocked'."// Test #4
result = validateTransition(
myStateMachine,
'open',
'open',
{
allowSelfTransition: true,
}
);// result will be true (this is a valid transition even though it's not explicitly defined)
console.assert(result);
```## Options
The `validateTransition` function accepts an optional `options` object as its fourth argument. The following options are available:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `allowSelfTransition` | `boolean` | `true` | If `true`, a transition from a state to itself will be considered valid. |
| `throwErrors` | `boolean` | `false` | If `true`, an error will be thrown if the transition is invalid. |