-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.js
117 lines (90 loc) · 2.57 KB
/
index.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
const EMPTY_CHAIN = null;
const END_MARKER = '\0';
module.exports = (rules) => {
let firstSets = {};
let followSets = {};
let predictSets = {};
rules.map(({ left }) => {
firstSets[left] = [];
followSets[left] = [];
});
function union(arr1, arr2) {
return [...new Set([...arr1, ...arr2])];
}
function isNonterminal(item) {
return firstSets[item];
}
function collectSet(initialSet, items, additionalSet) {
let set = initialSet;
items.every((item, index) => {
if (isNonterminal(item)) {
set = union(set, firstSets[item].filter((setItem) => setItem !== EMPTY_CHAIN));
if (firstSets[item].includes(EMPTY_CHAIN)) {
if (items[index + 1]) return true;
set = union(set, additionalSet);
}
} else {
set = union(set, [item]);
}
});
return set;
}
function makeFirstSets() {
let isSetChanged;
do {
isSetChanged = false;
rules.forEach(({ left, right }) => {
let set = firstSets[left];
set = union(set, collectSet(set, right, [EMPTY_CHAIN]));
if (firstSets[left].length !== set.length) {
firstSets[left] = set;
isSetChanged = true;
}
});
} while (isSetChanged);
return firstSets;
}
function makeFollowSets() {
followSets[rules[0].left].push(END_MARKER);
let isSetChanged;
do {
isSetChanged = false;
rules.forEach(({ left, right }) => {
right.forEach((item, index) => {
if (!isNonterminal(item)) return;
let set = followSets[item];
set = union(
set,
index + 1 < right.length
? collectSet(set, right.slice(index + 1), followSets[left])
: followSets[left],
);
if (followSets[item].length !== set.length) {
followSets[item] = set;
isSetChanged = true;
}
});
});
} while (isSetChanged);
return followSets;
}
function makePredictSets() {
rules.forEach(({ left, right }, ruleIndex) => {
const firstItem = right[0];
let set = [];
if (isNonterminal(firstItem)) {
set = union(set, collectSet(set, right, followSets[left]));
} else if (firstItem === EMPTY_CHAIN) {
set = [...followSets[left]];
} else {
set.push(firstItem);
}
predictSets[ruleIndex + 1] = set;
});
return predictSets;
}
firstSets = makeFirstSets();
followSets = makeFollowSets();
predictSets = makePredictSets();
return { firstSets, followSets, predictSets };
};