MCPcopy Create free account
hub / github.com/cortex-js/compute-engine / levenshtein

Function levenshtein

src/common/fuzzy-string-match.ts:2–27  ·  view source on GitHub ↗

Calculate the Levenshtein distance between two strings using a two-row optimization

(source: string, target: string)

Source from the content-addressed store, hash-verified

1/**
2 * Optimal string alignment distance (restricted Damerau–Levenshtein: handles
3 * substitution, insertion, deletion, and adjacent transposition). Bails out
4 * early, returning `max + 1`, once the distance is known to exceed `max`.
5 */
6export function osaDistance(a: string, b: string, max: number): number {
7 const la = a.length;
8 const lb = b.length;
9 if (Math.abs(la - lb) > max) return max + 1;
10 if (la === 0) return lb;
11 if (lb === 0) return la;
12
13 let prevPrev = new Array<number>(lb + 1);
14 let prev = new Array<number>(lb + 1);
15 let curr = new Array<number>(lb + 1);
16 for (let j = 0; j <= lb; j++) prev[j] = j;
17
18 for (let i = 1; i <= la; i++) {
19 curr[0] = i;
20 let rowMin = curr[0];
21 for (let j = 1; j <= lb; j++) {
22 const cost = a[i - 1] === b[j - 1] ? 0 : 1;
23 let v = Math.min(
24 prev[j] + 1, // deletion
25 curr[j - 1] + 1, // insertion
26 prev[j - 1] + cost // substitution
27 );
28 if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1])
29 v = Math.min(v, prevPrev[j - 2] + 1); // transposition
30 curr[j] = v;

Callers 1

fuzzyStringMatchFunction · 0.85

Calls 1

fromMethod · 0.45

Tested by

no test coverage detected