Skip to content

Instantly share code, notes, and snippets.

@bspaulding
Created November 29, 2018 20:55
Show Gist options
  • Save bspaulding/f2463ecbfbd547277672445d078e8d37 to your computer and use it in GitHub Desktop.
Save bspaulding/f2463ecbfbd547277672445d078e8d37 to your computer and use it in GitHub Desktop.
// Levenshtein Distance
// https://en.wikipedia.org/wiki/Levenshtein_distance
function distance(a, b) {
if (!a.length || !b.length) {
return 0;
}
const cost = a[a.length - 1] === b[b.length - 1] ? 0 : 1;
const atrim = a.slice(0, a.length - 1);
const btrim = b.slice(0, b.length - 1);
return Math.min(
distance(atrim, b) + 1,
distance(a, btrim) + 1,
distance(atrim, btrim) + cost
);
}
distance("sitting", "kitten") === 3;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment