Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Created September 5, 2018 11:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WebReflection/a1e2302a6900b5879bed40cebeb956e8 to your computer and use it in GitHub Desktop.
Save WebReflection/a1e2302a6900b5879bed40cebeb956e8 to your computer and use it in GitHub Desktop.
Levenshtein distance
// (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