1 | const array = [];
|
2 | const characterCodeCache = [];
|
3 |
|
4 | export default function leven(first, second) {
|
5 | if (first === second) {
|
6 | return 0;
|
7 | }
|
8 |
|
9 | const swap = first;
|
10 |
|
11 |
|
12 |
|
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 |
|
22 |
|
23 |
|
24 |
|
25 | while (firstLength > 0 && (first.charCodeAt(~-firstLength) === second.charCodeAt(~-secondLength))) {
|
26 | firstLength--;
|
27 | secondLength--;
|
28 | }
|
29 |
|
30 |
|
31 |
|
32 |
|
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 |
|
67 | result = array[index] = temporary > result ? (temporary2 > result ? result + 1 : temporary2) : (temporary2 > temporary ? temporary + 1 : temporary2);
|
68 | }
|
69 | }
|
70 |
|
71 | return result;
|
72 | }
|