forked from rauschma/enumify
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstate-machine.test.ts
More file actions
113 lines (102 loc) · 2.66 KB
/
state-machine.test.ts
File metadata and controls
113 lines (102 loc) · 2.66 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import {Enum, EnumValue} from '../src/ts-enums';
class Result extends EnumValue {
constructor(name: string) {
super(name);
}
}
class ResultEnumType extends Enum<Result> {
ACCEPTED: Result = new Result('ACCEPTED');
REJECTED: Result = new Result('REJECTED');
constructor() {
super();
this.initEnum('Result');
}
}
const ResultEnum: ResultEnumType = new ResultEnumType();
class State extends EnumValue {
constructor(
name: string,
private _enter: {(iter: IterableIterator<string>): State | Result}
) {
super(name);
}
enter(iter: IterableIterator<string>): State | Result {
return this._enter(iter);
}
}
class StateEnumType extends Enum<State> {
START: State = new State('START', (iter: IterableIterator<string>):
| State
| Result => {
const {value, done} = iter.next();
if (done) {
return ResultEnum.REJECTED;
}
switch (value) {
case 'A':
return StateEnum.A_SEQUENCE;
default:
return ResultEnum.REJECTED;
}
});
A_SEQUENCE: State = new State('A_SEQUENCE', (iter: IterableIterator<string>):
| State
| Result => {
const {value, done} = iter.next();
if (done) {
return ResultEnum.REJECTED;
}
switch (value) {
case 'A':
return StateEnum.A_SEQUENCE;
case 'B':
return StateEnum.B_SEQUENCE;
default:
return ResultEnum.REJECTED;
}
});
B_SEQUENCE: State = new State('B_SEQUENCE', (iter: IterableIterator<string>):
| State
| Result => {
const {value, done} = iter.next();
if (done) {
return StateEnum.ACCEPT;
}
switch (value) {
case 'B':
return StateEnum.B_SEQUENCE;
default:
return ResultEnum.REJECTED;
}
});
ACCEPT: State = new State('ACCEPT', (): State | Result => {
return ResultEnum.ACCEPTED;
});
constructor() {
super();
this.initEnum('State');
}
}
const StateEnum: StateEnumType = new StateEnumType();
describe('state machine', () => {
function runStateMachine(str: string): boolean {
let iter: IterableIterator<string> = str[Symbol.iterator]();
let state: State | Result = StateEnum.START;
while (true) {
if (state === ResultEnum.ACCEPTED) {
return true;
} else if (state === ResultEnum.REJECTED) {
return false;
} else {
state = (state as State).enter(iter);
}
}
}
it('should accept and reject properly', () => {
expect(runStateMachine('AABBB')).toBe(true);
expect(runStateMachine('AA')).toBe(false);
expect(runStateMachine('BBB')).toBe(false);
expect(runStateMachine('AABBC')).toBe(false);
expect(runStateMachine('')).toBe(false);
});
});