Last active
May 5, 2025 12:25
-
-
Save keesey/e09d0af833476385b9ee13b6d26a2b84 to your computer and use it in GitHub Desktop.
Levenshtein distance implemented in TypeScript
This file contains hidden or 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
export function levenshtein(a: string, b: string): number | |
{ | |
const an = a ? a.length : 0; | |
const bn = b ? b.length : 0; | |
if (an === 0) | |
{ | |
return bn; | |
} | |
if (bn === 0) | |
{ | |
return an; | |
} | |
const matrix = new Array<number[]>(bn + 1); | |
for (let i = 0; i <= bn; ++i) | |
{ | |
let row = matrix[i] = new Array<number>(an + 1); | |
row[0] = i; | |
} | |
const firstRow = matrix[0]; | |
for (let j = 1; j <= an; ++j) | |
{ | |
firstRow[j] = j; | |
} | |
for (let i = 1; i <= bn; ++i) | |
{ | |
for (let j = 1; j <= an; ++j) | |
{ | |
if (b.charAt(i - 1) === a.charAt(j - 1)) | |
{ | |
matrix[i][j] = matrix[i - 1][j - 1]; | |
} | |
else | |
{ | |
matrix[i][j] = Math.min( | |
matrix[i - 1][j - 1], // substitution | |
matrix[i][j - 1], // insertion | |
matrix[i - 1][j] // deletion | |
) + 1; | |
} | |
} | |
} | |
return matrix[bn][an]; | |
}; |
Would you mind if I used this in an NPM package that I'm developing? Credit will be given above the function of course.
Would you mind if I used this in an NPM package that I'm developing? Credit will be given above the function of course.
I am certain I just translated this from someone else's implementation in another language. Wish I could remember.
You can have it, no need to credit me.
Cleaned up a little, and honored noUncheckedIndexedAccess
export function levenshtein(a: string, b: string) {
const an = a.length
const bn = b.length
if (an == 0) {
return bn
}
if (bn == 0) {
return an
}
const matrix = new Array<number[]>(bn + 1)
for (let i = 0; i <= bn; ++i) {
const row = (matrix[i] = new Array<number>(an + 1))
row[0] = i
}
const firstRow = matrix[0]
for (let j = 1; j <= an; ++j) {
firstRow![j] = j
}
for (let i = 1; i <= bn; ++i) {
for (let j = 1; j <= an; ++j) {
if (b.charAt(i - 1) === a.charAt(j - 1)) {
matrix[i]![j] = matrix[i - 1]![j - 1]!
} else {
matrix[i]![j] =
Math.min(
matrix[i - 1]![j - 1]!, // substitution
matrix[i]![j - 1]!, // insertion
matrix[i - 1]![j]! // deletion
) + 1
}
}
}
return matrix[bn]![an]!
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very simple and practical implementation of the Levenshtein algorithm ! Thanks