-
Notifications
You must be signed in to change notification settings - Fork 1
/
levenshtein-search.js
386 lines (340 loc) · 10.6 KB
/
levenshtein-search.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
const { searchExact, reverse } = require('./utils')
function isEditDistanceNoGreaterThan (a, b, maxDist) {
if (a.length > b.length) {
[a, b] = [b, a]
}
const lenDelta = b.length - a.length
if (lenDelta > maxDist) {
return false
}
if (maxDist === 0) {
return a === b
}
let firstDiffIdx
for (firstDiffIdx = 0; firstDiffIdx < a.length; firstDiffIdx++) {
if (a[firstDiffIdx] !== b[firstDiffIdx]) break
}
if (firstDiffIdx === a.length) {
return lenDelta <= maxDist
}
let lastDiffIdx
for (lastDiffIdx = a.length - 1; lastDiffIdx >= 0; lastDiffIdx--) {
if (a[lastDiffIdx] !== b[lastDiffIdx + lenDelta]) break
}
a = a.slice(firstDiffIdx, lastDiffIdx + 1)
b = b.slice(firstDiffIdx, lastDiffIdx + 1 + lenDelta)
const [dist, length] = _expand(a, b, maxDist)
return dist + (b.length - length) <= maxDist
}
function editDistance (a, b) {
if (a.length > b.length) {
[a, b] = [b, a]
}
const scores = new Array(a.length + 1)
for (let i = 0; i <= a.length; i++) {
scores[i] = i
}
let _prevScore
let prevScore
for (let i = 0; i < b.length; i++) {
scores[0] = i + 1
prevScore = i
for (let k = 0; k < a.length; k++) {
_prevScore = scores[k + 1]
scores[k + 1] = Math.min(
prevScore + +(a[k] !== b[i]),
scores[k] + 1,
scores[k + 1] + 1
)
prevScore = _prevScore
}
}
return scores[a.length]
}
function makeChar2needleIdx (needle, maxDist) {
const res = {}
for (let i = Math.min(needle.length - 1, maxDist); i >= 0; i--) {
res[needle[i]] = i
}
return res
}
function * fuzzySearch (needle, haystack, maxDist) {
if (needle.length > haystack.length + maxDist) return
const ngramLen = Math.floor(needle.length / (maxDist + 1))
if (maxDist === 0) {
for (const index of searchExact(needle, haystack)) {
yield {
start: index,
end: index + needle.length,
dist: 0
}
}
} else if (ngramLen >= 10) {
yield * fuzzySearchNgrams(needle, haystack, maxDist)
} else {
yield * fuzzySearchCandidates(needle, haystack, maxDist)
}
}
function _expand (needle, haystack, maxDist) {
maxDist = +maxDist
let firstDiff
for (firstDiff = 0; firstDiff < Math.min(needle.length, haystack.length); firstDiff++) {
if (needle.charCodeAt(firstDiff) !== haystack.charCodeAt(firstDiff)) break
}
if (firstDiff) {
needle = needle.slice(firstDiff)
haystack = haystack.slice(firstDiff)
}
if (!needle) {
return [0, firstDiff]
} else if (!haystack) {
if (needle.length <= maxDist) {
return [needle.length, firstDiff]
} else {
return [null, null]
}
}
if (maxDist === 0) return [null, null]
let scores = new Array(needle.length + 1)
for (let i = 0; i <= maxDist; i++) {
scores[i] = i
}
let newScores = new Array(needle.length + 1)
let minScore = null
let minScoreIdx = null
let maxGoodScore = maxDist
let firstGoodScoreIdx = 0
let lastGoodScoreIdx = needle.length - 1
for (let haystackIdx = 0; haystackIdx < haystack.length; haystackIdx++) {
const char = haystack.charCodeAt(haystackIdx)
const needleIdxStart = Math.max(0, firstGoodScoreIdx - 1)
const needleIdxLimit = Math.min(
haystackIdx + maxDist,
needle.length - 1,
lastGoodScoreIdx
)
newScores[0] = scores[0] + 1
firstGoodScoreIdx = newScores[0] <= maxGoodScore ? 0 : null
lastGoodScoreIdx = newScores[0] <= maxGoodScore ? 0 : -1
let needleIdx
for (needleIdx = needleIdxStart; needleIdx < needleIdxLimit; needleIdx++) {
const score = newScores[needleIdx + 1] = Math.min(
scores[needleIdx] + +(char !== needle.charCodeAt(needleIdx)),
scores[needleIdx + 1] + 1,
newScores[needleIdx] + 1
)
if (score <= maxGoodScore) {
if (firstGoodScoreIdx === null) firstGoodScoreIdx = needleIdx + 1
lastGoodScoreIdx = Math.max(
lastGoodScoreIdx,
needleIdx + 1 + (maxGoodScore - score)
)
}
}
const lastScore = newScores[needleIdx + 1] = Math.min(
scores[needleIdx] + +(char !== needle.charCodeAt(needleIdx)),
newScores[needleIdx] + 1
)
if (lastScore <= maxGoodScore) {
if (firstGoodScoreIdx === null) firstGoodScoreIdx = needleIdx + 1
lastGoodScoreIdx = needleIdx + 1
}
if (
needleIdx === needle.length - 1 &&
(minScore === null || lastScore <= minScore)
) {
minScore = lastScore
minScoreIdx = haystackIdx
if (minScore < maxGoodScore) maxGoodScore = minScore
}
[scores, newScores] = [newScores, scores]
if (firstGoodScoreIdx === null) break
}
if (minScore !== null && minScore <= maxDist) {
return [minScore, minScoreIdx + 1 + firstDiff]
} else {
return [null, null]
}
}
function * fuzzySearchNgrams (needle, haystack, maxDist) {
// use n-gram search
const ngramLen = Math.floor(needle.length / (maxDist + 1))
const needleLen = needle.length
const haystackLen = haystack.length
for (let ngramStartIdx = 0;
ngramStartIdx <= needle.length - ngramLen;
ngramStartIdx += ngramLen
) {
const ngram = needle.slice(ngramStartIdx, ngramStartIdx + ngramLen)
const ngramEnd = ngramStartIdx + ngramLen
const needleBeforeReversed = reverse(needle.slice(0, ngramStartIdx))
const needleAfter = needle.slice(ngramEnd)
const startIdx = Math.max(0, ngramStartIdx - maxDist)
const endIdx = Math.min(haystackLen, haystackLen - needleLen + ngramEnd + maxDist)
for (const haystackMatchIdx of searchExact(ngram, haystack, startIdx, endIdx)) {
// try to expand left
const [distRight, rightExpandSize] = _expand(
needleAfter,
haystack.slice(
haystackMatchIdx + ngramLen,
haystackMatchIdx - ngramStartIdx + needleLen + maxDist
),
maxDist
)
if (distRight === null) continue
const [distLeft, leftExpandSize] = _expand(
needleBeforeReversed,
reverse(haystack.slice(
Math.max(0, haystackMatchIdx - ngramStartIdx - (maxDist - distRight)),
haystackMatchIdx
)),
maxDist - distRight
)
if (distLeft === null) continue
yield {
start: haystackMatchIdx - leftExpandSize,
end: haystackMatchIdx + ngramLen + rightExpandSize,
dist: distLeft + distRight
}
}
}
}
function * fuzzySearchCandidates (needle, haystack, maxDist) {
const debugFlag = false
if (debugFlag) console.log(`fuzzySearchCandidates(${needle}, ${haystack}, ${maxDist})`)
// prepare some often used things in advance
const needleLen = needle.length
const haystackLen = haystack.length
if (needleLen > haystackLen + maxDist) return
const char2needleIdx = makeChar2needleIdx(needle, maxDist)
let prevCandidates = [] // candidates from the last iteration
let candidates = [] // new candidates from the current iteration
// iterate over the chars in the haystack, updating the candidates for each
for (let i = 0; i < haystack.length; i++) {
const haystackChar = haystack[i]
prevCandidates = candidates
candidates = []
const needleIdx = char2needleIdx[haystackChar]
if (needleIdx !== undefined) {
if (needleIdx + 1 === needleLen) {
if (debugFlag) {
console.log(`yield ${{
start: i,
end: i + 1,
dist: needleIdx
}}`)
}
yield {
start: i,
end: i + 1,
dist: needleIdx
}
} else {
candidates.push({
startIdx: i,
needleIdx: needleIdx + 1,
dist: needleIdx
})
}
}
for (const candidate of prevCandidates) {
// if this sequence char is the candidate's next expected char
if (needle[candidate.needleIdx] === haystackChar) {
// if reached the end of the needle, return a match
if (candidate.needleIdx + 1 === needleLen) {
if (debugFlag) {
console.log(`yield ${{
start: candidate.startIdx,
end: i + 1,
dist: candidate.dist
}}`)
}
yield {
start: candidate.startIdx,
end: i + 1,
dist: candidate.dist
}
} else {
// otherwise, update the candidate's needleIdx and keep it
candidates.push({
startIdx: candidate.startIdx,
needleIdx: candidate.needleIdx + 1,
dist: candidate.dist
})
}
} else {
if (candidate.dist === maxDist) continue
candidates.push({
startIdx: candidate.startIdx,
needleIdx: candidate.needleIdx,
dist: candidate.dist + 1
})
for (let nSkipped = 1; nSkipped <= maxDist - candidate.dist; nSkipped++) {
if (candidate.needleIdx + nSkipped === needleLen) {
if (debugFlag) {
console.log(`yield ${{
start: candidate.startIdx,
end: i + 1,
dist: candidate.dist + nSkipped
}}`)
}
yield {
start: candidate.startIdx,
end: i + 1,
dist: candidate.dist + nSkipped
}
break
} else if (needle[candidate.needleIdx + nSkipped] === haystackChar) {
if (candidate.needleIdx + nSkipped + 1 === needleLen) {
if (debugFlag) {
console.log(`yield ${{
start: candidate.startIdx,
end: i + 1,
dist: candidate.dist + nSkipped
}}`)
}
yield {
start: candidate.startIdx,
end: i + 1,
dist: candidate.dist + nSkipped
}
} else {
candidates.push({
startIdx: candidate.startIdx,
needleIdx: candidate.needleIdx + 1 + nSkipped,
dist: candidate.dist + nSkipped
})
}
break
}
}
if (i + 1 < haystackLen && candidate.needleIdx + 1 < needleLen) {
candidates.push({
startIdx: candidate.startIdx,
needleIdx: candidate.needleIdx + 1,
dist: candidate.dist + 1
})
}
}
}
if (debugFlag) console.log(candidates)
}
for (const candidate of candidates) {
candidate.dist += needle.length - candidate.needleIdx
if (candidate.dist <= maxDist) {
yield {
start: candidate.startIdx,
end: haystack.length,
dist: candidate.dist
}
}
}
}
module.exports = {
_expand,
editDistance,
fuzzySearch,
fuzzySearchNgrams,
fuzzySearchCandidates,
isEditDistanceNoGreaterThan
}