Skip to content

Instantly share code, notes, and snippets.

@bperel
Forked from andrei-m/levenshtein.js
Last active April 23, 2017 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bperel/3d7dad5d7a0370d52a42a6f898ec938f to your computer and use it in GitHub Desktop.
Save bperel/3d7dad5d7a0370d52a42a6f898ec938f to your computer and use it in GitHub Desktop.
Levenshtein distance between two given strings implemented in JavaScript and usable as a Node.js module
// https://gist.github.com/andrei-m/982927#gistcomment-1931258 looks like the fastest Levenshtein implementation
const levenshtein = (a, b) => {
if (a.length === 0) return b.length
if (b.length === 0) return a.length
let tmp, i, j, prev, val
// swap to save some memory O(min(a,b)) instead of O(a)
if (a.length > b.length) {
tmp = a
a = b
b = tmp
}
row = Array(a.length + 1)
// init the row
for (i = 0; i <= a.length; i++) {
row[i] = i
}
// fill in the rest
for (i = 1; i <= b.length; i++) {
prev = i
for (j = 1; j <= a.length; j++) {
if (b[i-1] === a[j-1]) {
val = row[j-1] // match
} else {
val = Math.min(row[j-1] + 1, // substitution
Math.min(prev + 1, // insertion
row[j] + 1)) // deletion
}
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