Levenshtein Edit Distance

Compute the minimum number of insertions, deletions, and substitutions between two strings, the basis of fuzzy matching and spell suggestions.

JavascriptData Integrity

Code

javascriptsnippet
17 lines
export function levenshtein(a, b) {
  if (a === b) return 0;
  const rows = a.length + 1;
  const cols = b.length + 1;
  const prev = new Array(cols);
  const curr = new Array(cols);
  for (let j = 0; j < cols; j++) prev[j] = j;
  for (let i = 1; i < rows; i++) {
    curr[0] = i;
    for (let j = 1; j < cols; j++) {
      const cost = a[i - 1] === b[j - 1] ? 0 : 1;
      curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);
    }
    for (let j = 0; j < cols; j++) prev[j] = curr[j];
  }
  return prev[cols - 1];
}

How it works

Count the function levenshtein as the entire surface area of Levenshtein Edit Distance.

The structure is a loop within a loop: for (let j = 0; j < cols; j++) prev[j] = j; outside, for (let i = 1; i < rows; i++) inside.

Points of care

  • The guard a === b short-circuits the flow with an early return when its condition holds.

Applying it

Entry signature: export function levenshtein(a, b)

The surface worth importing is levenshtein; the helpers around it are private to the snippet.

Statements that matter

if (a === b) return 0;
return prev[cols - 1];

Interactive Tools for This Topic

FAQ

Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. The file defines `levenshtein` at load time.