Created
September 5, 2018 11:33
-
-
Save WebReflection/a1e2302a6900b5879bed40cebeb956e8 to your computer and use it in GitHub Desktop.
Levenshtein distance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// (c) 2018 Andrea Giammarchi | |
function levenshtein(from, to) | |
{ | |
const fromLength = from.length + 1; | |
const toLength = to.length + 1; | |
const size = fromLength * toLength; | |
const grid = new Array(size); | |
let x = 0; | |
let y = 0; | |
let X = 0; | |
let Y = 0; | |
let crow = 0; | |
grid[0] = 0; | |
while (++x < toLength) | |
grid[x] = x; | |
while (++y < fromLength) | |
{ | |
X = x = 0; | |
const prow = crow; | |
crow = y * toLength; | |
grid[crow + x] = y; | |
while (++x < toLength) | |
{ | |
const del = grid[prow + x] + 1; | |
const ins = grid[crow + X] + 1; | |
const sub = grid[prow + X] + (from[Y] === to[X] ? 0 : 1); | |
grid[crow + x] = del < ins ? | |
(del < sub ? | |
del : sub) : | |
(ins < sub ? | |
ins : sub); | |
++X; | |
} | |
Y = y; | |
} | |
return grid[size - 1]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment