-
Notifications
You must be signed in to change notification settings - Fork 0
/
base-state-machine.ts
43 lines (34 loc) · 1.12 KB
/
base-state-machine.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { StateMachine, TransitionTable, InvalidStateTransitionException } from './state-machine';
export class BaseStateMachine<T> implements StateMachine<T> {
public stateHistory: T[] = [];
private privateCurrentState: T;
constructor(private transitionTable: TransitionTable<T>, initialState: T) {
this.stateHistory.push(initialState);
this.privateCurrentState = initialState;
}
public get currentState(): T {
return this.privateCurrentState;
}
public set currentState(value: T) {
this.goTo(value);
}
public goTo(state: T): void {
if (this.isValidTransition(state)) {
this.privateCurrentState = state;
this.stateHistory.push(this.privateCurrentState);
} else {
throw new InvalidStateTransitionException(
`Transition table does not allow change: ${this.privateCurrentState} -> ${state}`,
);
}
}
private isValidTransition(state: T): boolean {
const stateSet = new Set<T>();
this.transitionTable.forEach((entry) => {
if (entry[0] === this.privateCurrentState) {
stateSet.add(entry[1]);
}
});
return stateSet.has(state);
}
}