/
suffix_patricia_tree.ts
322 lines (301 loc) · 7.83 KB
/
suffix_patricia_tree.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
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
type Edge = {
id: number;
start: number;
end: number | "#";
to: Node;
};
type Node = {
id: number;
edges: { [key: string]: Edge };
suffixLink: Node | undefined;
};
type SuffixPatriciaTree = {
str: string;
root: Node;
};
let currentID = 0;
function getID(): number {
const r = currentID;
currentID++;
return r;
}
function showGraph(
node: Node,
depth: number,
buffer: string,
str: string
): string {
const indent = " ".repeat(depth);
buffer += `${indent}Node ${node.id} suffixLink:`;
if (node.suffixLink !== undefined) {
buffer += `${node.suffixLink.id},`;
} else {
buffer += "undefined,";
}
buffer += "\n";
for (const key in node.edges) {
const edge = node.edges[key];
const edgeStr =
edge.end == "#"
? str.substring(edge.start)
: str.substring(edge.start, edge.end);
buffer += `${indent} Edge id:${edge.id} start:${edge.start} end:${edge.end} edgeStr:${edgeStr} to.id:${edge.to.id}\n`;
buffer += showGraph(edge.to, depth + 1, "", str);
}
return buffer;
}
function ukkonenAlgorithm(str: string): SuffixPatriciaTree {
const ROOT_NODE_ID = getID();
let suffixTrie: SuffixPatriciaTree = {
str: str,
root: {
id: ROOT_NODE_ID,
edges: {},
suffixLink: undefined,
},
};
let remainder = 0;
let activeNode = suffixTrie.root;
let activeEdge = "";
let activeLength = 0;
for (let currentIndex = 0; currentIndex < str.length; currentIndex++) {
remainder++;
let lastNewNode: Node | undefined = undefined;
while (remainder > 0) {
if (activeLength == 0) {
activeEdge = str[currentIndex];
}
if (activeNode.edges[activeEdge] === undefined) {
activeNode.edges[activeEdge] = {
id: getID(),
start: currentIndex,
end: "#",
to: {
id: getID(),
edges: {},
suffixLink: undefined,
},
};
} else {
const activeEdgeStart = activeNode.edges[activeEdge].start;
const activeEdgeEnd = activeNode.edges[activeEdge].end;
const activeEdgeStr =
activeEdgeEnd == "#"
? str.substring(
activeNode.edges[activeEdge].start,
currentIndex + 1
)
: str.substring(activeNode.edges[activeEdge].start, activeEdgeEnd);
// Proceed activeNode.
if (activeLength >= activeEdgeStr.length) {
activeNode = activeNode.edges[activeEdge].to;
activeLength -= activeEdgeStr.length;
activeEdge = str[activeEdgeStart + activeEdgeStr.length];
continue;
}
// Current character is already in the tree.
if (activeEdgeStr[activeLength] == str[currentIndex]) {
activeLength++;
break;
}
// Split edge
const originalEdges = {};
for (const k of Object.keys(activeNode.edges[activeEdge].to.edges)) {
originalEdges[k] = activeNode.edges[activeEdge].to.edges[k];
}
activeNode.edges[activeEdge].to.edges = {};
activeNode.edges[activeEdge].end = activeEdgeStart + activeLength;
activeNode.edges[activeEdge].to.edges[activeEdgeStr[activeLength]] = {
id: getID(),
start: activeEdgeStart + activeLength,
end: activeEdgeEnd,
to: {
id: getID(),
edges: originalEdges,
suffixLink: undefined,
},
};
activeNode.edges[activeEdge].to.edges[str[currentIndex]] = {
id: getID(),
start: currentIndex,
end: "#",
to: {
id: getID(),
edges: {},
suffixLink: undefined,
},
};
if (lastNewNode !== undefined) {
lastNewNode.suffixLink = activeNode.edges[activeEdge].to;
}
lastNewNode = activeNode.edges[activeEdge].to;
}
remainder--;
if (activeNode.id == ROOT_NODE_ID && activeLength > 0) {
activeLength--;
activeEdge = str[currentIndex - remainder + 1];
} else if (activeNode.id != ROOT_NODE_ID) {
if (activeNode.suffixLink != undefined) {
activeNode = activeNode.suffixLink;
} else {
activeNode = suffixTrie.root;
}
}
}
}
return suffixTrie;
}
type Match = { start: number; end: number; score: number };
const MAX_MATCHES = 20;
const SCORE_REWARD_MATCHED = 8;
const SCORE_REWARD_UNMATCHED = -3;
function getEdgeLength(
edge: Edge,
suffixPatriciaTree: SuffixPatriciaTree
): number {
if (edge.end == "#") {
return suffixPatriciaTree.str.length - edge.start;
} else {
return edge.end - edge.start;
}
}
function fuzzySearchDFS(
pattern: string,
patternIndex: number,
suffixPatriciaTree: SuffixPatriciaTree,
edge: Edge,
edgeIndex: number,
score: number,
consumed: number,
maxConsumed: number,
matches: Set<string>
): Set<string> {
const edgeStr =
edge.end == "#"
? suffixPatriciaTree.str.substring(edge.start)
: suffixPatriciaTree.str.substring(edge.start, edge.end);
if (matches.size >= MAX_MATCHES) {
return matches;
} else if (getEdgeLength(edge, suffixPatriciaTree) <= edgeIndex) {
for (const [_, e] of Object.entries(edge.to.edges)) {
const ms = fuzzySearchDFS(
pattern,
patternIndex,
suffixPatriciaTree,
e,
0,
score,
consumed,
maxConsumed,
new Set<string>()
);
for (const m of ms) {
matches.add(m);
}
}
return matches;
} else if (patternIndex === pattern.length) {
const end = edge.start + edgeIndex;
matches.add(
JSON.stringify({
start: end - consumed,
end: end,
score: score,
})
);
return matches;
} else if (consumed == maxConsumed) {
return matches;
} else if (
// Option to care about case
pattern[patternIndex].toLowerCase() === edgeStr[edgeIndex].toLowerCase()
) {
const ms1 = fuzzySearchDFS(
pattern,
patternIndex,
suffixPatriciaTree,
edge,
edgeIndex + 1,
score + SCORE_REWARD_UNMATCHED,
consumed + 1,
maxConsumed,
new Set<string>()
);
for (const m of ms1) {
matches.add(m);
}
const ms2 = fuzzySearchDFS(
pattern,
patternIndex + 1,
suffixPatriciaTree,
edge,
edgeIndex + 1,
score + SCORE_REWARD_MATCHED,
consumed + 1,
maxConsumed,
new Set<string>()
);
for (const m of ms2) {
matches.add(m);
}
return matches;
} else {
return fuzzySearchDFS(
pattern,
patternIndex,
suffixPatriciaTree,
edge,
edgeIndex + 1,
score + SCORE_REWARD_UNMATCHED,
consumed + 1,
maxConsumed,
matches
);
}
}
function fuzzySearchSuffixPatriciaTree(
pattern: string,
maxExtraChars: number,
suffixPatriciaTree: SuffixPatriciaTree
): Match[] {
let matches: Match[] = [];
for (const [str, edge] of Object.entries(suffixPatriciaTree.root.edges)) {
if (str.toLowerCase() === pattern[0].toLowerCase()) {
const ms = fuzzySearchDFS(
pattern,
1,
suffixPatriciaTree,
edge,
1,
SCORE_REWARD_MATCHED,
1,
pattern.length + maxExtraChars,
new Set<string>()
);
for (const m of ms) {
matches.push(JSON.parse(m));
}
} else {
const ms = fuzzySearchDFS(
pattern,
0,
suffixPatriciaTree,
edge,
1,
SCORE_REWARD_MATCHED,
1,
pattern.length + maxExtraChars,
new Set<string>()
);
for (const m of ms) {
matches.push(JSON.parse(m));
}
}
}
matches.sort((a, b) => {
return b.score - a.score;
});
return matches;
}
export type { Edge, Node, SuffixPatriciaTree, Match };
export { ukkonenAlgorithm, showGraph, fuzzySearchSuffixPatriciaTree };