Newer
Older
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
var fsm = function () {
const debugging = false;
const debug = function (msg) {
if (debugging) {
console.log(msg);
}
};
/**
* a fsm that tries to match string "abb". see function
* matchesSubstringAbb.
*/
const matchAbbMachine = function () {
this.stateWaitForA = "wait for a";
this.stateWaitForFirstB = "wait for 1st b";
this.stateWaitForSecondB = "wait for 2nd b";
this.stateSucceed = "succeed";
this.currentState = "wait for a";
this.readch = function (ch) {
switch (this.currentState) {
case this.stateWaitForA:
if (ch === 'a') {
this.currentState = this.stateWaitForFirstB;
} else {
this.currentState = this.stateWaitForA;
}
break;
case this.stateWaitForFirstB:
if (ch === 'b') {
this.currentState = this.stateWaitForSecondB;
} else if (ch === 'a') {
// do nothing, keep current state.
} else {
this.currentState = this.stateWaitForA;
}
break;
case this.stateWaitForSecondB:
if (ch === 'b') {
this.currentState = this.stateSucceed;
} else if (ch === 'a') {
this.currentState = this.stateWaitForFirstB;
} else {
this.currentState = this.stateWaitForA;
}
break;
case this.succeed:
// do nothing, keep current state.
break;
}
debug("readch " + ch + ", currentState is " + this.currentState);
return this.currentState;
};
};
/**
* return true if given string has substring "abb" in it.
* implemented using fsm.
*/
const matchesSubstringAbb = function (str) {
var machine = new matchAbbMachine();
for (i = 0; i < str.length; ++i) {
machine.readch(str[i]);
if (machine.currentState === "succeed") {
// console.log("matches");
return true;
}
}
return false;
};
return {
matchesSubstringAbb: matchesSubstringAbb
};
}();