Skip to content

Instantly share code, notes, and snippets.

@Xhamps
Created May 7, 2018 19:42
Show Gist options
  • Save Xhamps/b948b1438bdf58e359fdc3616212cbac to your computer and use it in GitHub Desktop.
Save Xhamps/b948b1438bdf58e359fdc3616212cbac to your computer and use it in GitHub Desktop.
// Based off https://en.wikipedia.org/wiki/Levenshtein_distance
// No optimization, really.
function levenshtein(a, b) {
/* base case: empty strings */
if (a.length == 0) {
return b.length;
}
if (b.length == 0) {
return a.length;
}
// Test if last characters of the strings match.
const cost = a[a.length - 1] == b[b.length - 1] ? 0 : 1;
/* return minimum of delete char from s, delete char from t, and delete char from both */
return Math.min(levenshtein(a.slice(0, -1), b) + 1, levenshtein(a, b.slice(0, -1)) + 1, levenshtein(a.slice(0, -1), b.slice(0, -1)) + cost);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment