| 1 | const { min } = Math; |
| 2 | |
| 3 | // a minimal leven distance implementation |
| 4 | // balanced maintenability with code size |
| 5 | // It is not blazingly fast but should be okay for Babel user case |
| 6 | // where it will be run for at most tens of time on strings |
| 7 | // that have less than 20 ASCII characters |
| 8 | |
| 9 | // https://rosettacode.org/wiki/Levenshtein_distance#ES5 |
| 10 | function levenshtein(a: string, b: string): number { |
| 11 | let t = [], |
| 12 | u: number[] = [], |
| 13 | i, |
| 14 | j; |
| 15 | const m = a.length, |
| 16 | n = b.length; |
| 17 | if (!m) { |
| 18 | return n; |
| 19 | } |
| 20 | if (!n) { |
| 21 | return m; |
| 22 | } |
| 23 | for (j = 0; j <= n; j++) { |
| 24 | t[j] = j; |
| 25 | } |
| 26 | for (i = 1; i <= m; i++) { |
| 27 | for (u = [i], j = 1; j <= n; j++) { |
| 28 | u[j] = |
| 29 | a[i - 1] === b[j - 1] ? t[j - 1] : min(t[j - 1], t[j], u[j - 1]) + 1; |
| 30 | } |
| 31 | t = u; |
| 32 | } |
| 33 | return u[n]; |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * Given a string `str` and an array of candidates `arr`, |
| 38 | * return the first of elements in candidates that has minimal |
| 39 | * Levenshtein distance with `str`. |
| 40 | * @export |
| 41 | * @param {string} str |
| 42 | * @param {string[]} arr |
| 43 | * @returns {string} |
| 44 | */ |
| 45 | export function findSuggestion(str: string, arr: readonly string[]): string { |
| 46 | const distances = arr.map<number>(el => levenshtein(el, str)); |
| 47 | return arr[distances.indexOf(min(...distances))]; |
| 48 | } |