-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy pathsearcher.js
396 lines (348 loc) · 9.04 KB
/
searcher.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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
//
// Match functions
//
let fuzzyRegexp,
i,
index,
lastIndex,
match,
matcher,
matchIndex,
matchLength,
queryLength,
score,
separators,
value,
valueLength;
const SEPARATOR = ".";
let query =
(queryLength =
value =
valueLength =
matcher = // current match function
fuzzyRegexp = // query fuzzy regexp
index = // position of the query in the string being matched
lastIndex = // last position of the query in the string being matched
match = // regexp match data
matchIndex =
matchLength =
score = // score for the current match
separators = // counter
i =
null); // cursor
function exactMatch() {
index = value.indexOf(query);
if (!(index >= 0)) {
return;
}
lastIndex = value.lastIndexOf(query);
if (index !== lastIndex) {
return Math.max(
scoreExactMatch(),
((index = lastIndex) && scoreExactMatch()) || 0,
);
} else {
return scoreExactMatch();
}
}
function scoreExactMatch() {
// Remove one point for each unmatched character.
score = 100 - (valueLength - queryLength);
if (index > 0) {
// If the character preceding the query is a dot, assign the same score
// as if the query was found at the beginning of the string, minus one.
if (value.charAt(index - 1) === SEPARATOR) {
score += index - 1;
// Don't match a single-character query unless it's found at the beginning
// of the string or is preceded by a dot.
} else if (queryLength === 1) {
return;
// (1) Remove one point for each unmatched character up to the nearest
// preceding dot or the beginning of the string.
// (2) Remove one point for each unmatched character following the query.
} else {
i = index - 2;
while (i >= 0 && value.charAt(i) !== SEPARATOR) {
i--;
}
score -=
index -
i + // (1)
(valueLength - queryLength - index); // (2)
}
// Remove one point for each dot preceding the query, except for the one
// immediately before the query.
separators = 0;
i = index - 2;
while (i >= 0) {
if (value.charAt(i) === SEPARATOR) {
separators++;
}
i--;
}
score -= separators;
}
// Remove five points for each dot following the query.
separators = 0;
i = valueLength - queryLength - index - 1;
while (i >= 0) {
if (value.charAt(index + queryLength + i) === SEPARATOR) {
separators++;
}
i--;
}
score -= separators * 5;
return Math.max(1, score);
}
function fuzzyMatch() {
if (valueLength <= queryLength || value.includes(query)) {
return;
}
if (!(match = fuzzyRegexp.exec(value))) {
return;
}
matchIndex = match.index;
matchLength = match[0].length;
score = scoreFuzzyMatch();
if (
(match = fuzzyRegexp.exec(
value.slice((i = value.lastIndexOf(SEPARATOR) + 1)),
))
) {
matchIndex = i + match.index;
matchLength = match[0].length;
return Math.max(score, scoreFuzzyMatch());
} else {
return score;
}
}
function scoreFuzzyMatch() {
// When the match is at the beginning of the string or preceded by a dot.
if (matchIndex === 0 || value.charAt(matchIndex - 1) === SEPARATOR) {
return Math.max(66, 100 - matchLength);
// When the match is at the end of the string.
} else if (matchIndex + matchLength === valueLength) {
return Math.max(33, 67 - matchLength);
// When the match is in the middle of the string.
} else {
return Math.max(1, 34 - matchLength);
}
}
//
// Searchers
//
app.Searcher = class Searcher extends Events {
static CHUNK_SIZE = 20000;
static DEFAULTS = {
max_results: app.config.max_results,
fuzzy_min_length: 3,
};
static SEPARATORS_REGEXP =
/#|:-|->|\$(?=\w)|\-(?=\w)|\:(?=\w)|\ [\/\-&]\ |:\ |\ /g;
static EOS_SEPARATORS_REGEXP = /(\w)[\-:]$/;
static INFO_PARANTHESES_REGEXP = /\ \(\w+?\)$/;
static EMPTY_PARANTHESES_REGEXP = /\(\)/;
static EVENT_REGEXP = /\ event$/;
static DOT_REGEXP = /\.+/g;
static WHITESPACE_REGEXP = /\s/g;
static EMPTY_STRING = "";
static ELLIPSIS = "...";
static STRING = "string";
static normalizeString(string) {
return string
.toLowerCase()
.replace(Searcher.ELLIPSIS, Searcher.EMPTY_STRING)
.replace(Searcher.EVENT_REGEXP, Searcher.EMPTY_STRING)
.replace(Searcher.INFO_PARANTHESES_REGEXP, Searcher.EMPTY_STRING)
.replace(Searcher.SEPARATORS_REGEXP, SEPARATOR)
.replace(Searcher.DOT_REGEXP, SEPARATOR)
.replace(Searcher.EMPTY_PARANTHESES_REGEXP, Searcher.EMPTY_STRING)
.replace(Searcher.WHITESPACE_REGEXP, Searcher.EMPTY_STRING);
}
static normalizeQuery(string) {
string = this.normalizeString(string);
return string.replace(Searcher.EOS_SEPARATORS_REGEXP, "$1.");
}
constructor(options) {
super();
this.options = { ...Searcher.DEFAULTS, ...(options || {}) };
}
find(data, attr, q) {
this.kill();
this.data = data;
this.attr = attr;
this.query = q;
this.setup();
if (this.isValid()) {
this.match();
} else {
this.end();
}
}
setup() {
query = this.query = this.constructor.normalizeQuery(this.query);
queryLength = query.length;
this.dataLength = this.data.length;
this.matchers = [exactMatch];
this.totalResults = 0;
this.setupFuzzy();
}
setupFuzzy() {
if (queryLength >= this.options.fuzzy_min_length) {
fuzzyRegexp = this.queryToFuzzyRegexp(query);
this.matchers.push(fuzzyMatch);
} else {
fuzzyRegexp = null;
}
}
isValid() {
return queryLength > 0 && query !== SEPARATOR;
}
end() {
if (!this.totalResults) {
this.triggerResults([]);
}
this.trigger("end");
this.free();
}
kill() {
if (this.timeout) {
clearTimeout(this.timeout);
this.free();
}
}
free() {
this.data = null;
this.attr = null;
this.dataLength = null;
this.matchers = null;
this.matcher = null;
this.query = null;
this.totalResults = null;
this.scoreMap = null;
this.cursor = null;
this.timeout = null;
}
match() {
if (!this.foundEnough() && (this.matcher = this.matchers.shift())) {
this.setupMatcher();
this.matchChunks();
} else {
this.end();
}
}
setupMatcher() {
this.cursor = 0;
this.scoreMap = new Array(101);
}
matchChunks() {
this.matchChunk();
if (this.cursor === this.dataLength || this.scoredEnough()) {
this.delay(() => this.match());
this.sendResults();
} else {
this.delay(() => this.matchChunks());
}
}
matchChunk() {
({ matcher } = this);
for (let j = 0, end = this.chunkSize(); j < end; j++) {
value = this.data[this.cursor][this.attr];
if (value.split) {
// string
valueLength = value.length;
if ((score = matcher())) {
this.addResult(this.data[this.cursor], score);
}
} else {
// array
score = 0;
for (value of Array.from(this.data[this.cursor][this.attr])) {
valueLength = value.length;
score = Math.max(score, matcher() || 0);
}
if (score > 0) {
this.addResult(this.data[this.cursor], score);
}
}
this.cursor++;
}
}
chunkSize() {
if (this.cursor + Searcher.CHUNK_SIZE > this.dataLength) {
return this.dataLength % Searcher.CHUNK_SIZE;
} else {
return Searcher.CHUNK_SIZE;
}
}
scoredEnough() {
return this.scoreMap[100]?.length >= this.options.max_results;
}
foundEnough() {
return this.totalResults >= this.options.max_results;
}
addResult(object, score) {
let name;
(
this.scoreMap[(name = Math.round(score))] || (this.scoreMap[name] = [])
).push(object);
this.totalResults++;
}
getResults() {
const results = [];
for (let j = this.scoreMap.length - 1; j >= 0; j--) {
var objects = this.scoreMap[j];
if (objects) {
results.push(...objects);
}
}
return results.slice(0, this.options.max_results);
}
sendResults() {
const results = this.getResults();
if (results.length) {
this.triggerResults(results);
}
}
triggerResults(results) {
this.trigger("results", results);
}
delay(fn) {
return (this.timeout = setTimeout(fn, 1));
}
queryToFuzzyRegexp(string) {
const chars = string.split("");
for (i = 0; i < chars.length; i++) {
var char = chars[i];
chars[i] = $.escapeRegexp(char);
}
return new RegExp(chars.join(".*?")); // abc -> /a.*?b.*?c.*?/
}
};
app.SynchronousSearcher = class SynchronousSearcher extends app.Searcher {
match() {
if (this.matcher) {
if (!this.allResults) {
this.allResults = [];
}
this.allResults.push(...this.getResults());
}
return super.match(...arguments);
}
free() {
this.allResults = null;
return super.free(...arguments);
}
end() {
this.sendResults(true);
return super.end(...arguments);
}
sendResults(end) {
if (end && this.allResults?.length) {
return this.triggerResults(this.allResults);
}
}
delay(fn) {
return fn();
}
};