Repository navigation
Expand file tree
/
Copy patheditDistance.js
More file actions
58 lines (49 loc) · 1.54 KB
/
Copy patheditDistance.js
File metadata and controls
58 lines (49 loc) · 1.54 KB
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
// Note: The metric used here is Damerau–Levenshtein distance.
// This metric imposes a uniform cost for insertion, deletion,
// substitutions, and transposition, as these compose the most
// common human typing mistakes.
var editDistance = function(str1, str2) {
if (str1 === str2) {
return 0;
}
if (!str1.length || !str2.length) {
return str1.length || str2.length;
}
// Swap strings so can just focus on one
if (str2.length > str1.length) {
var temp = str1;
str1 = str2;
str2 = temp;
}
var len1 = str1.length;
var len2 = str2.length;
var prevPrevRow;
var prevRow = [];
// Fill in previous row with empty subsequences.
for (var col = 0; col <= len2; col++) {
prevRow[col] = col;
}
var currRow = [1];
// Fake iterating through the whole matrix,
// but remembering only two rows at a time.
for (var row = 1; row <= len1; row++) {
for (var col = 1; col <= len2; col++) {
// If two strings match at their final character, their LCS
// is the LCS of their prefixes, plus that final character.
if (str1[row-1] === str2[col-1]) {
currRow[col] = prevRow[col-1];
// Otherwise, their LCS is the best LCS that results from
// trimming either of their final characters, plus one.
} else {
var del = prevRow[col] + 1;
var ins = currRow[col-1] + 1;
var sub = prevRow[col-1] + 1;
currRow[col] = Math.min(del, ins, sub);
}
}
prevPrevRow = prevRow;
prevRow = currRow;
currRow = [row + 1];
}
return prevRow[len2];
};