suggestionList.js.flow 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // @flow strict
  2. /**
  3. * Given an invalid input string and a list of valid options, returns a filtered
  4. * list of valid options sorted based on their similarity with the input.
  5. */
  6. export default function suggestionList(
  7. input: string,
  8. options: $ReadOnlyArray<string>,
  9. ): Array<string> {
  10. const optionsByDistance = Object.create(null);
  11. const inputThreshold = input.length / 2;
  12. for (const option of options) {
  13. const distance = lexicalDistance(input, option);
  14. const threshold = Math.max(inputThreshold, option.length / 2, 1);
  15. if (distance <= threshold) {
  16. optionsByDistance[option] = distance;
  17. }
  18. }
  19. return Object.keys(optionsByDistance).sort(
  20. (a, b) => optionsByDistance[a] - optionsByDistance[b],
  21. );
  22. }
  23. /**
  24. * Computes the lexical distance between strings A and B.
  25. *
  26. * The "distance" between two strings is given by counting the minimum number
  27. * of edits needed to transform string A into string B. An edit can be an
  28. * insertion, deletion, or substitution of a single character, or a swap of two
  29. * adjacent characters.
  30. *
  31. * Includes a custom alteration from Damerau-Levenshtein to treat case changes
  32. * as a single edit which helps identify mis-cased values with an edit distance
  33. * of 1.
  34. *
  35. * This distance can be useful for detecting typos in input or sorting
  36. *
  37. * @param {string} a
  38. * @param {string} b
  39. * @return {int} distance in number of edits
  40. */
  41. function lexicalDistance(aStr, bStr) {
  42. if (aStr === bStr) {
  43. return 0;
  44. }
  45. const d = [];
  46. const a = aStr.toLowerCase();
  47. const b = bStr.toLowerCase();
  48. const aLength = a.length;
  49. const bLength = b.length;
  50. // Any case change counts as a single edit
  51. if (a === b) {
  52. return 1;
  53. }
  54. for (let i = 0; i <= aLength; i++) {
  55. d[i] = [i];
  56. }
  57. for (let j = 1; j <= bLength; j++) {
  58. d[0][j] = j;
  59. }
  60. for (let i = 1; i <= aLength; i++) {
  61. for (let j = 1; j <= bLength; j++) {
  62. const cost = a[i - 1] === b[j - 1] ? 0 : 1;
  63. d[i][j] = Math.min(
  64. d[i - 1][j] + 1,
  65. d[i][j - 1] + 1,
  66. d[i - 1][j - 1] + cost,
  67. );
  68. if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
  69. d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);
  70. }
  71. }
  72. }
  73. return d[aLength][bLength];
  74. }