@@ -127,3 +127,52 @@ export function underscore(str: string): string {
127
127
export function capitalize ( str : string ) : string {
128
128
return str . charAt ( 0 ) . toUpperCase ( ) + str . substr ( 1 ) ;
129
129
}
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