Levenshtein Edit Distance CLI
A zero-dependency Node CLI that computes the Levenshtein edit distance between two strings, with a rolled one-row dynamic program and unit tests.
Project
node-levenshtein-cli
Entry point: levenshtein.mjs
Install
node --versionRun
node levenshtein.mjs kitten sittingTest
node --test levenshtein.test.mjsExpected output
Prints the integer edit distance between the two arguments, for example 3 for kitten and sitting.Dependencies
- node >=20
What it does
Computes the minimum number of single-character insertions, deletions, or substitutions to turn one string into another. The implementation keeps only one row of the dynamic-programming table, so memory is O(min length) instead of O(n*m).
export function levenshtein(a, b) {
if (a === b) return 0;
if (a.length === 0) return b.length;
if (b.length === 0) return a.length;
let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
for (let i = 1; i <= a.length; i++) {
const curr = [i];
for (let j = 1; j <= b.length; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
curr[j] = Math.min(curr[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
}
prev = curr;
}
return prev[b.length];
}
const [a, b] = process.argv.slice(2);
if (a === undefined || b === undefined) { console.error('usage: levenshtein <a> <b>'); process.exit(1); }
console.log(levenshtein(a, b));
Run and verify
node levenshtein.mjs kitten sitting
Run the test command to check the implementation: node --test levenshtein.test.mjs.
Expected Output
For kitten and sitting the distance is 3 (k→s, e→i, and insert g). The program prints exactly one integer:
3
Limitations
Operates on UTF-16 code units, so a single emoji or accented grapheme may count as more than one unit. Use a grapheme splitter before calling it if that matters for your input.