Created
November 29, 2018 20:55
-
-
Save bspaulding/f2463ecbfbd547277672445d078e8d37 to your computer and use it in GitHub Desktop.
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
// 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