1.0.1 • Published 2 years ago
@hoolmgreen/finate-state-machine v1.0.1
@hoolmgreen/finate-state-machine
Prerequisites
Node.js must be installed. See Downloading and installing Node.js and npm
Installation
npm install @hoolmgreen/finate-state-machine
Example
package.json
{
"scripts": {
"compile": "tsc fsm-test.ts",
"test": "node fsm-test.js"
},
"dependencies": {
"typescript": "^5.3.2",
"@hoolmgreen/finate-state-machine": "^1.0.1"
}
}
fsm-test.ts
import {HooAction, HooEvent, HooMachine, HooState, HooTransition} from '@hoolmgreen/finate-state-machine';
interface SomeInfo {
someInfo: string;
}
class OnState extends HooState {
}
class OffState extends HooState {
}
class BlinkState extends HooState {
}
class OffEvent extends HooEvent {
}
class OnEvent extends HooEvent {
}
class BlinkEvent extends HooEvent {
}
class TestEvent extends HooEvent {
}
class OnAction extends HooAction {
perform(data : any) : boolean {
super.perform(data);
const someInfo = data as SomeInfo;
console.log("'OnAction "+(someInfo.someInfo ? someInfo.someInfo : "none")+"'");
return true;
}
}
class OffAction extends HooAction {
perform(data : any) : boolean {
super.perform(data);
const someInfo = data as SomeInfo;
console.log("'OffAction "+(someInfo.someInfo ? someInfo.someInfo : "none")+"'");
return true;
}
}
class BlinkAction extends HooAction {
perform(data : any) : boolean {
super.perform(data);
const someInfo = data as SomeInfo;
console.log("'BlinkAction "+(someInfo.someInfo ? someInfo.someInfo : "none")+"'");
return true;
}
}
const onEvent = new OnEvent();
const offEvent = new OffEvent();
const blinkEvent = new BlinkEvent();
const testEvent = new TestEvent();
class MyMachine extends HooMachine {
constructor(data: any = {}) {
const offState = new OffState();
const onState = new OnState();
const blinkState = new BlinkState();
const states = [offState, onState, blinkState];
const transitions = [
new HooTransition(onEvent, offState, onState, new OnAction()),
new HooTransition(blinkEvent, offState, blinkState, new BlinkAction()),
new HooTransition(offEvent, onState, offState, new OffAction()),
new HooTransition(blinkEvent, onState, blinkState, new BlinkAction()),
new HooTransition(onEvent, blinkState, onState, new OnAction()),
new HooTransition(offEvent, blinkState, offState, new OffAction())
];
super(states, transitions, offState, data);
}
}
const machine = new MyMachine({ someInfo: "someInfo" });
try {
machine.dispatch(onEvent);
machine.dispatch(blinkEvent);
machine.dispatch(onEvent);
machine.dispatch(offEvent);
machine.dispatch(blinkEvent);
machine.dispatch(offEvent);
machine.dispatch(testEvent);
}
catch (e) {
console.log(e.toString());
}