UNPKG

1.87 kBJavaScriptView Raw
1const array = [];
2const characterCodeCache = [];
3
4export default function leven(first, second) {
5 if (first === second) {
6 return 0;
7 }
8
9 const swap = first;
10
11 // Swapping the strings if `a` is longer than `b` so we know which one is the
12 // shortest & which one is the longest
13 if (first.length > second.length) {
14 first = second;
15 second = swap;
16 }
17
18 let firstLength = first.length;
19 let secondLength = second.length;
20
21 // Performing suffix trimming:
22 // We can linearly drop suffix common to both strings since they
23 // don't increase distance at all
24 // Note: `~-` is the bitwise way to perform a `- 1` operation
25 while (firstLength > 0 && (first.charCodeAt(~-firstLength) === second.charCodeAt(~-secondLength))) {
26 firstLength--;
27 secondLength--;
28 }
29
30 // Performing prefix trimming
31 // We can linearly drop prefix common to both strings since they
32 // don't increase distance at all
33 let start = 0;
34
35 while (start < firstLength && (first.charCodeAt(start) === second.charCodeAt(start))) {
36 start++;
37 }
38
39 firstLength -= start;
40 secondLength -= start;
41
42 if (firstLength === 0) {
43 return secondLength;
44 }
45
46 let bCharacterCode;
47 let result;
48 let temporary;
49 let temporary2;
50 let index = 0;
51 let index2 = 0;
52
53 while (index < firstLength) {
54 characterCodeCache[index] = first.charCodeAt(start + index);
55 array[index] = ++index;
56 }
57
58 while (index2 < secondLength) {
59 bCharacterCode = second.charCodeAt(start + index2);
60 temporary = index2++;
61 result = index2;
62
63 for (index = 0; index < firstLength; index++) {
64 temporary2 = bCharacterCode === characterCodeCache[index] ? temporary : temporary + 1;
65 temporary = array[index];
66 // eslint-disable-next-line no-multi-assign
67 result = array[index] = temporary > result ? (temporary2 > result ? result + 1 : temporary2) : (temporary2 > temporary ? temporary + 1 : temporary2);
68 }
69 }
70
71 return result;
72}