Skip to content

Instantly share code, notes, and snippets.

@MarioBinder
Created August 8, 2022 06:01
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
levenshtein.ts
export function levenshtein(a: string, b: string): number {
if (!a.length) {
return b.length;
}
/* c8 ignore next 3 */
if (!b.length) {
return a.length;
}
let tmp;
if (a.length > b.length) {
tmp = a;
a = b;
b = tmp;
}
const row = Array.from({ length: a.length + 1 }, (_, i) => i);
let val = 0;
for (let i = 1; i <= b.length; i++) {
let prev = i;
for (let j = 1; j <= a.length; j++) {
if (b[i - 1] === a[j - 1]) {
val = row[j - 1];
} else {
val = Math.min(row[j - 1] + 1, Math.min(prev + 1, row[j] + 1));
}
row[j - 1] = prev;
prev = val;
}
row[a.length] = prev;
}
return row[a.length];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment