Levenshtein Edit Distance
Compute the minimum number of insertions, deletions, and substitutions between two strings, the basis of fuzzy matching and spell suggestions.
Code
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 === bshort-circuits the flow with an earlyreturnwhen 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
Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.