Skip to content

Commit 4006366

Browse files
hanslBrocco
authored andcommitted
fix(@angular/cli): fix levenshtein distance
1 parent b4f611c commit 4006366

1 file changed

Lines changed: 13 additions & 26 deletions

File tree

packages/@angular/cli/models/command-runner.ts

Lines changed: 13 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -59,39 +59,26 @@ export async function runCommand(commandMap: CommandMap,
5959
}
6060

6161
if (!Cmd) {
62+
// Based off https://en.wikipedia.org/wiki/Levenshtein_distance
63+
// No optimization, really.
6264
function levenshtein(a: string, b: string): number {
63-
if (a.length === 0) {
65+
/* base case: empty strings */
66+
if (a.length == 0) {
6467
return b.length;
6568
}
66-
if (b.length === 0) {
69+
if (b.length == 0) {
6770
return a.length;
6871
}
6972

70-
if (a.length > b.length) {
71-
let tmp = a;
72-
a = b;
73-
b = tmp;
74-
}
75-
76-
const row = Array(a.length);
77-
for (let i = 0; i <= a.length; i++) {
78-
row[i] = i;
79-
}
80-
81-
let result: number;
82-
for (let i = 1; i <= b.length; i++) {
83-
result = i;
84-
85-
for (let j = 1; j <= a.length; j++) {
86-
let tmp = row[j - 1];
87-
row[j - 1] = result;
88-
result = b[i - 1] === a[j - 1]
89-
? tmp
90-
: Math.min(tmp + 1, Math.min(result + 1, row[j] + 1));
91-
}
92-
}
73+
// Test if last characters of the strings match.
74+
const cost = a[a.length - 1] == b[b.length - 1] ? 0 : 1;
9375

94-
return result;
76+
/* return minimum of delete char from s, delete char from t, and delete char from both */
77+
return Math.min(
78+
levenshtein(a.slice(0, -1), b) + 1,
79+
levenshtein(a, b.slice(0, -1)) + 1,
80+
levenshtein(a.slice(0, -1), b.slice(0, -1)) + cost,
81+
);
9582
}
9683

9784
const commandsDistance = {} as { [name: string]: number };

0 commit comments

Comments
 (0)