fuzzy.ts 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. /**
  2. * Fuzzy matching utilities.
  3. * Matches if all query characters appear in order (not necessarily consecutive).
  4. * Lower score = better match.
  5. */
  6. export interface FuzzyMatch {
  7. matches: boolean;
  8. score: number;
  9. }
  10. export function fuzzyMatch(query: string, text: string): FuzzyMatch {
  11. const queryLower = query.toLowerCase();
  12. const textLower = text.toLowerCase();
  13. const matchQuery = (normalizedQuery: string): FuzzyMatch => {
  14. if (normalizedQuery.length === 0) {
  15. return { matches: true, score: 0 };
  16. }
  17. if (normalizedQuery.length > textLower.length) {
  18. return { matches: false, score: 0 };
  19. }
  20. let queryIndex = 0;
  21. let score = 0;
  22. let lastMatchIndex = -1;
  23. let consecutiveMatches = 0;
  24. for (let i = 0; i < textLower.length && queryIndex < normalizedQuery.length; i++) {
  25. if (textLower[i] === normalizedQuery[queryIndex]) {
  26. const isWordBoundary = i === 0 || /[\s\-_./:]/.test(textLower[i - 1]!);
  27. // Reward consecutive matches
  28. if (lastMatchIndex === i - 1) {
  29. consecutiveMatches++;
  30. score -= consecutiveMatches * 5;
  31. } else {
  32. consecutiveMatches = 0;
  33. // Penalize gaps
  34. if (lastMatchIndex >= 0) {
  35. score += (i - lastMatchIndex - 1) * 2;
  36. }
  37. }
  38. // Reward word boundary matches
  39. if (isWordBoundary) {
  40. score -= 10;
  41. }
  42. // Slight penalty for later matches
  43. score += i * 0.1;
  44. lastMatchIndex = i;
  45. queryIndex++;
  46. }
  47. }
  48. if (queryIndex < normalizedQuery.length) {
  49. return { matches: false, score: 0 };
  50. }
  51. if (normalizedQuery === textLower) {
  52. score -= 100;
  53. }
  54. return { matches: true, score };
  55. };
  56. const primaryMatch = matchQuery(queryLower);
  57. if (primaryMatch.matches) {
  58. return primaryMatch;
  59. }
  60. const alphaNumericMatch = queryLower.match(/^(?<letters>[a-z]+)(?<digits>[0-9]+)$/);
  61. const numericAlphaMatch = queryLower.match(/^(?<digits>[0-9]+)(?<letters>[a-z]+)$/);
  62. const swappedQuery = alphaNumericMatch
  63. ? `${alphaNumericMatch.groups?.digits ?? ""}${alphaNumericMatch.groups?.letters ?? ""}`
  64. : numericAlphaMatch
  65. ? `${numericAlphaMatch.groups?.letters ?? ""}${numericAlphaMatch.groups?.digits ?? ""}`
  66. : "";
  67. if (!swappedQuery) {
  68. return primaryMatch;
  69. }
  70. const swappedMatch = matchQuery(swappedQuery);
  71. if (!swappedMatch.matches) {
  72. return primaryMatch;
  73. }
  74. return { matches: true, score: swappedMatch.score + 5 };
  75. }
  76. /**
  77. * Filter and sort items by fuzzy match quality (best matches first).
  78. * Supports space-separated tokens: all tokens must match.
  79. */
  80. export function fuzzyFilter<T>(items: T[], query: string, getText: (item: T) => string): T[] {
  81. if (!query.trim()) {
  82. return items;
  83. }
  84. const tokens = query
  85. .trim()
  86. .split(/\s+/)
  87. .filter((t) => t.length > 0);
  88. if (tokens.length === 0) {
  89. return items;
  90. }
  91. const results: { item: T; totalScore: number }[] = [];
  92. for (const item of items) {
  93. const text = getText(item);
  94. let totalScore = 0;
  95. let allMatch = true;
  96. for (const token of tokens) {
  97. const match = fuzzyMatch(token, text);
  98. if (match.matches) {
  99. totalScore += match.score;
  100. } else {
  101. allMatch = false;
  102. break;
  103. }
  104. }
  105. if (allMatch) {
  106. results.push({ item, totalScore });
  107. }
  108. }
  109. results.sort((a, b) => a.totalScore - b.totalScore);
  110. return results.map((r) => r.item);
  111. }