-
Notifications
You must be signed in to change notification settings - Fork 0
/
finite-automata.js
101 lines (80 loc) · 2.83 KB
/
finite-automata.js
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
class FiniteAutomata {
constructor() {
this._idStack = [0];
this._rootState = null;
}
provisionId() {
let retId = 0;
if (this._idStack.length === 1) {
retId = this._idStack[0]++;
} else {
retId = this._idStack.pop();
}
return retId;
}
deprovisionId(id) {
this._idStack.push(id);
}
setRootState(node) {
this._rootState = node;
}
getRootState() {
return this._rootState;
}
prettyPrint() {
if (this._rootState === null) {
return;
}
let visitedStates = new Set([this._rootState.getId()]);
let prettyStates = [];
this._prettyPrintHelper(this._rootState, visitedStates, prettyStates);
for (let i = 0; i < prettyStates.length; ++i) {
const prettyState = prettyStates[i];
if (i !== 0) {
console.log('');
}
console.log(`STATE ${prettyState.id}:`);
for (const transitionPair of prettyState.transitionMap) {
console.log(`\t"${transitionPair[0]}": ${transitionPair[1]}`);
}
if (prettyState.epsilonTransitions.length > 0) {
console.log(`\t"ε": ${prettyState.epsilonTransitions}`);
}
}
}
_prettyPrintHelper(currentState, visitedStates, prettyStates) {
let prettyState = {
id: currentState.getId()
, transitionMap: []
, epsilonTransitions: []
};
let visitStates = [];
for (const chars in currentState._transitionMap) {
if (!currentState._transitionMap.hasOwnProperty(chars)) {
continue;
}
const transitionStates = currentState._transitionMap[chars];
let prettyTransitionStates = [];
for (const transitionState of transitionStates) {
const transitionStateId = transitionState.getId();
prettyTransitionStates.push(transitionStateId);
visitStates.push(transitionState);
}
prettyState.transitionMap.push([chars, prettyTransitionStates]);
}
for (const epsilonTransition of currentState._epsilonTransitions) {
const epsilonTransitionId = epsilonTransition.getId();
prettyState.epsilonTransitions.push(epsilonTransitionId);
visitStates.push(epsilonTransition);
}
prettyStates.push(prettyState);
for (const visitState of visitStates) {
const visitStateId = visitState.getId();
if (!visitedStates.has(visitStateId)) {
visitedStates.add(visitStateId);
this._prettyPrintHelper(visitState, visitedStates, prettyStates);
}
}
}
}
module.exports = FiniteAutomata;