| 14308 | } |
| 14309 | // Adapted from: https://github.com/dcporter/didyoumean.js/blob/master/didYouMean-1.2.1.js |
| 14310 | static _getEditDistance(stringA, stringB, maxInt) { |
| 14311 | // Handle null or undefined max. |
| 14312 | maxInt = maxInt || maxInt === 0 ? maxInt : Utils.MAX_INT |
| 14313 | const aLength = stringA.length |
| 14314 | const bLength = stringB.length |
| 14315 | // Fast path - no A or B. |
| 14316 | if (aLength === 0) return Math.min(maxInt + 1, bLength) |
| 14317 | if (bLength === 0) return Math.min(maxInt + 1, aLength) |
| 14318 | // Fast path - length diff larger than max. |
| 14319 | if (Math.abs(aLength - bLength) > maxInt) return maxInt + 1 |
| 14320 | // Slow path. |
| 14321 | const matrix = [] |
| 14322 | // Set up the first row ([0, 1, 2, 3, etc]). |
| 14323 | for (let bIndex = 0; bIndex <= bLength; bIndex++) { |
| 14324 | matrix[bIndex] = [bIndex] |
| 14325 | } |
| 14326 | // Set up the first column (same). |
| 14327 | for (let aIndex = 0; aIndex <= aLength; aIndex++) { |
| 14328 | matrix[0][aIndex] = aIndex |
| 14329 | } |
| 14330 | let colMin |
| 14331 | let minJ |
| 14332 | let maxJ |
| 14333 | // Loop over the rest of the columns. |
| 14334 | for (let bIndex = 1; bIndex <= bLength; bIndex++) { |
| 14335 | colMin = Utils.MAX_INT |
| 14336 | minJ = 1 |
| 14337 | if (bIndex > maxInt) minJ = bIndex - maxInt |
| 14338 | maxJ = bLength + 1 |
| 14339 | if (maxJ > maxInt + bIndex) maxJ = maxInt + bIndex |
| 14340 | // Loop over the rest of the rows. |
| 14341 | for (let aIndex = 1; aIndex <= aLength; aIndex++) { |
| 14342 | // If j is out of bounds, just put a large value in the slot. |
| 14343 | if (aIndex < minJ || aIndex > maxJ) matrix[bIndex][aIndex] = maxInt + 1 |
| 14344 | // Otherwise do the normal Levenshtein thing. |
| 14345 | else { |
| 14346 | // If the characters are the same, there's no change in edit distance. |
| 14347 | if (stringB.charAt(bIndex - 1) === stringA.charAt(aIndex - 1)) matrix[bIndex][aIndex] = matrix[bIndex - 1][aIndex - 1] |
| 14348 | // Otherwise, see if we're substituting, inserting or deleting. |
| 14349 | else |
| 14350 | matrix[bIndex][aIndex] = Math.min( |
| 14351 | matrix[bIndex - 1][aIndex - 1] + 1, // Substitute |
| 14352 | Math.min( |
| 14353 | matrix[bIndex][aIndex - 1] + 1, // Insert |
| 14354 | matrix[bIndex - 1][aIndex] + 1 |
| 14355 | ) |
| 14356 | ) // Delete |
| 14357 | } |
| 14358 | // Either way, update colMin. |
| 14359 | if (matrix[bIndex][aIndex] < colMin) colMin = matrix[bIndex][aIndex] |
| 14360 | } |
| 14361 | // If this column's minimum is greater than the allowed maximum, there's no point |
| 14362 | // in going on with life. |
| 14363 | if (colMin > maxInt) return maxInt + 1 |
| 14364 | } |
| 14365 | // If we made it this far without running into the max, then return the final matrix value. |
| 14366 | return matrix[bLength][aLength] |
| 14367 | } |