2019-10-11 10:54:07 +03:00
|
|
|
# IT FSM
|
|
|
|
|
2019-10-19 20:27:06 +03:00
|
|
|
[![Build Status](https://travis-ci.com/icetemple/npm-it-fsm.svg?branch=master)](https://travis-ci.com/icetemple/npm-it-fsm)
|
2019-10-19 20:33:15 +03:00
|
|
|
[![Coverage Status](https://coveralls.io/repos/github/icetemple/npm-it-fsm/badge.svg?branch=master)](https://coveralls.io/github/icetemple/npm-it-fsm?branch=master)
|
2019-10-19 20:27:06 +03:00
|
|
|
|
2021-08-20 01:32:01 +03:00
|
|
|
Simple finite state machine
|
2019-10-17 13:54:15 +03:00
|
|
|
|
|
|
|
### Installation
|
|
|
|
|
|
|
|
`npm install --save it-fsm`
|
|
|
|
|
2021-08-20 01:32:01 +03:00
|
|
|
### Usage
|
2019-10-17 13:54:15 +03:00
|
|
|
|
2021-08-20 01:32:01 +03:00
|
|
|
```ts
|
|
|
|
import { StateMachineBuilder } from "it-fsm";
|
2019-10-17 13:54:15 +03:00
|
|
|
|
2021-08-20 01:32:01 +03:00
|
|
|
enum ProjectStatus {
|
|
|
|
Pending = "pending",
|
|
|
|
Active = "active",
|
|
|
|
Completed = "completed",
|
|
|
|
Archived = "archive",
|
|
|
|
}
|
2019-10-17 13:54:15 +03:00
|
|
|
|
2021-08-20 01:32:01 +03:00
|
|
|
const smbProject = new StateMachineBuilder()
|
|
|
|
.withStates(Object.values(ProjectStatus))
|
|
|
|
.withTransitions([
|
|
|
|
[ProjectStatus.Pending, [ProjectStatus.Active, ProjectStatus.Archived]],
|
|
|
|
[ProjectStatus.Active, [ProjectStatus.Completed]],
|
|
|
|
]);
|
2019-10-17 13:54:15 +03:00
|
|
|
|
2021-08-20 01:32:01 +03:00
|
|
|
async function main() {
|
|
|
|
const project1 = { id: 1, status: ProjectStatus.Pending };
|
|
|
|
const project2 = { id: 2, status: ProjectStatus.Completed };
|
2019-10-17 13:54:15 +03:00
|
|
|
|
2021-08-20 01:32:01 +03:00
|
|
|
// Build FSM with current project status
|
|
|
|
const smForProject1 = smbProject.build(project1.status);
|
|
|
|
const smForProject2 = smbProject.build(project2.status);
|
2019-10-17 13:54:15 +03:00
|
|
|
|
2021-08-20 01:32:01 +03:00
|
|
|
console.log(smForProject2.allowedTransitionStates()); // []
|
|
|
|
|
|
|
|
console.log(smForProject1.allowedTransitionStates()); // [active, archived]
|
|
|
|
await smForProject1.changeState(ProjectStatus.Active);
|
|
|
|
|
|
|
|
console.log(smForProject1.allowedTransitionStates()); // [completed]
|
|
|
|
await smForProject1.changeState(ProjectStatus.Completed);
|
|
|
|
|
|
|
|
console.log(smForProject1.allowedTransitionStates()); // []
|
2019-10-17 13:54:15 +03:00
|
|
|
}
|
2021-08-20 01:32:01 +03:00
|
|
|
|
|
|
|
main();
|
|
|
|
|
2019-10-17 13:54:15 +03:00
|
|
|
```
|