Skip to content

Commit 1b5c008

Browse files
hanslalexeagle
authored andcommitted
feat(@angular-devkit/core): add levenshtein distance utility
1 parent 0b84c1d commit 1b5c008

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

packages/angular_devkit/core/src/utils/strings.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,3 +127,52 @@ export function underscore(str: string): string {
127127
export function capitalize(str: string): string {
128128
return str.charAt(0).toUpperCase() + str.substr(1);
129129
}
130+
131+
/**
132+
* Calculate the levenshtein distance of two strings.
133+
* See https://en.wikipedia.org/wiki/Levenshtein_distance.
134+
* Based off https://gist.github.com/andrei-m/982927 (for using the faster dynamic programming
135+
* version).
136+
*
137+
* @param a String a.
138+
* @param b String b.
139+
* @returns A number that represents the distance between the two strings. The greater the number
140+
* the more distant the strings are from each others.
141+
*/
142+
export function levenshtein(a: string, b: string): number {
143+
if (a.length == 0) {
144+
return b.length;
145+
}
146+
if (b.length == 0) {
147+
return a.length;
148+
}
149+
150+
const matrix = [];
151+
152+
// increment along the first column of each row
153+
for (let i = 0; i <= b.length; i++) {
154+
matrix[i] = [i];
155+
}
156+
157+
// increment each column in the first row
158+
for (let j = 0; j <= a.length; j++) {
159+
matrix[0][j] = j;
160+
}
161+
162+
// Fill in the rest of the matrix
163+
for (let i = 1; i <= b.length; i++) {
164+
for (let j = 1; j <= a.length; j++) {
165+
if (b.charAt(i - 1) == a.charAt(j - 1)) {
166+
matrix[i][j] = matrix[i - 1][j - 1];
167+
} else {
168+
matrix[i][j] = Math.min(
169+
matrix[i - 1][j - 1] + 1, // substitution
170+
matrix[i][j - 1] + 1, // insertion
171+
matrix[i - 1][j] + 1, // deletion
172+
);
173+
}
174+
}
175+
}
176+
177+
return matrix[b.length][a.length];
178+
}

0 commit comments

Comments
 (0)