-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
72 lines (62 loc) · 1.56 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
/** @type {Array<number>} */
const codes = []
/** @type {Array<number>} */
const cache = []
/**
* Levenshtein edit distance.
*
* @param {string} value
* Primary value.
* @param {string} other
* Other value.
* @param {boolean} [insensitive=false]
* Compare insensitive to ASCII casing.
* @returns {number}
* Distance between `value` and `other`.
*/
export function levenshteinEditDistance(value, other, insensitive) {
if (value === other) {
return 0
}
if (value.length === 0) {
return other.length
}
if (other.length === 0) {
return value.length
}
if (insensitive) {
value = value.toLowerCase()
other = other.toLowerCase()
}
let index = 0
while (index < value.length) {
// eslint-disable-next-line unicorn/prefer-code-point
codes[index] = value.charCodeAt(index)
cache[index] = ++index
}
let indexOther = 0
/** @type {number} */
let result
while (indexOther < other.length) {
// eslint-disable-next-line unicorn/prefer-code-point
const code = other.charCodeAt(indexOther)
let index = -1
let distance = indexOther++
result = distance
while (++index < value.length) {
const distanceOther = code === codes[index] ? distance : distance + 1
distance = cache[index]
result =
distance > result
? distanceOther > result
? result + 1
: distanceOther
: distanceOther > distance
? distance + 1
: distanceOther
cache[index] = result
}
}
// @ts-expect-error: always assigned.
return result
}