-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2-autocorrect.js
51 lines (41 loc) · 1.27 KB
/
2-autocorrect.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
// Source: https://gist.github.com/andrei-m/982927#gistcomment-1796676
String.prototype.levenshtein = function(string) {
let a = this, b = string + "", m = [], i, j, min = Math.min;
if (!(a && b)) return (b || a).length;
for (i = 0; i <= b.length; m[i] = [i++]);
for (j = 0; j <= a.length; m[0][j] = j++);
for (i = 1; i <= b.length; i++) {
for (j = 1; j <= a.length; j++) {
m[i][j] = b.charAt(i - 1) == a.charAt(j - 1)
? m[i - 1][j - 1]
: m[i][j] = min(
m[i - 1][j - 1] + 1,
min(m[i][j - 1] + 1, m[i - 1 ][j]))
}
}
return m[b.length][a.length];
}
console.log("bat".levenshtein("bar"))
const dictionary = [
"banana",
"orange",
"apple",
"pear",
"mango",
"watermelon",
"pineapple"
]
function autocorrect(word) {
let shortestDistance = word.length
let correctWord = word
let currentDistance = 0
for (const dictionaryWord of dictionary) {
currentDistance = word.levenshtein(dictionaryWord)
if (currentDistance < shortestDistance) {
shortestDistance = currentDistance
correctWord = dictionaryWord
}
}
return correctWord
}
console.log(autocorrect("babana"))