Skip to content

Instantly share code, notes, and snippets.

@mohnish
Last active March 11, 2024 05:57
Show Gist options
  • Save mohnish/936f0fa3d783373784147b5e3dd48985 to your computer and use it in GitHub Desktop.
Save mohnish/936f0fa3d783373784147b5e3dd48985 to your computer and use it in GitHub Desktop.
Calculating Edit Distance between 2 strings using Levenshtein's algorithm
function editDistance(word1, word2) {
return levenshteinDistance(word1, word2, 0, 0);
}
function levenshteinDistance(word1, word2, i, j) {
if (i == word1.length) {
return word2.length - j;
} else if (j == word2.length) {
return word1.length - i;
} else {
let min = 0;
if (word1[i] == word2[j]) {
min = levenshteinDistance(word1, word2, i + 1, j + 1);
} else {
min = 1 + Math.min(
levenshteinDistance(word1, word2, i, j + 1),
levenshteinDistance(word1, word2, i + 1, j),
levenshteinDistance(word1, word2, i + 1, j + 1)
);
}
return min;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment