Open History to see the last commit
1export type RankedSearchResult<T> = {
2 item: T;
3 score: number;
4 tieBreaker: string;
5};
6
7export function normalizeSearchQuery(
8 input: string,
9 options?: {
10 trimLeadingPattern?: RegExp;
11 },
12): string {
13 const trimmed = input.trim();
14 if (!trimmed) {
15 return "";
16 }
17 return options?.trimLeadingPattern
18 ? trimmed.replace(options.trimLeadingPattern, "").toLowerCase()
19 : trimmed.toLowerCase();
20}
21
22export function scoreSubsequenceMatch(
23 value: string,
24 query: string,
25 options?: { ignorePosition?: boolean },
26): number | null {
27 if (!query) return 0;
28
29 let queryIndex = 0;
30 let firstMatchIndex = -1;
31 let previousMatchIndex = -1;
32 let gapPenalty = 0;
33
34 for (let valueIndex = 0; valueIndex < value.length; valueIndex += 1) {
35 if (value[valueIndex] !== query[queryIndex]) {
36 continue;
37 }
38
39 if (firstMatchIndex === -1) {
40 firstMatchIndex = valueIndex;
41 }
42 if (previousMatchIndex !== -1) {
43 gapPenalty += valueIndex - previousMatchIndex - 1;
44 }
45
46 previousMatchIndex = valueIndex;
47 queryIndex += 1;
48 if (queryIndex === query.length) {
49 const spanPenalty = valueIndex - firstMatchIndex + 1 - query.length;
50 if (options?.ignorePosition) {
51 return gapPenalty * 3 + spanPenalty;
52 }
53 const lengthPenalty = Math.min(64, value.length - query.length);
54 return firstMatchIndex * 2 + gapPenalty * 3 + spanPenalty + lengthPenalty;
55 }
56 }
57
58 return null;
59}
60
61function lengthPenalty(value: string, query: string): number {
62 return Math.min(64, Math.max(0, value.length - query.length));
63}
64
65function findBoundaryMatchIndex(
66 value: string,
67 query: string,
68 boundaryMarkers: readonly string[],
69): number | null {
70 let bestIndex: number | null = null;
71
72 for (const marker of boundaryMarkers) {
73 const index = value.indexOf(`${marker}${query}`);
74 if (index === -1) {
75 continue;
76 }
77
78 const matchIndex = index + marker.length;
79 if (bestIndex === null || matchIndex < bestIndex) {
80 bestIndex = matchIndex;
81 }
82 }
83
84 return bestIndex;
85}
86
87/**
88 * Scores how well `value` matches `query` using tiered match strategies.
89 *
90 * **Expects pre-normalized inputs**: both `value` and `query` must already be
91 * trimmed and lowercased (e.g. via {@link normalizeSearchQuery}).
92 */
93export function scoreQueryMatch(input: {
94 value: string;
95 query: string;
96 exactBase: number;
97 prefixBase?: number;
98 boundaryBase?: number;
99 includesBase?: number;
100 fuzzyBase?: number;
101 boundaryMarkers?: readonly string[];
102 /**
103 * Score by match tier alone, ignoring where the match lands and how long the
104 * value is, so callers can keep their own order among equal matches.
105 */
106 ignorePosition?: boolean;
107}): number | null {
108 const { value, query } = input;
109 const ignorePosition = input.ignorePosition === true;
110 const penalty = ignorePosition ? 0 : lengthPenalty(value, query);
111
112 if (!value || !query) {
113 return null;
114 }
115
116 if (value === query) {
117 return input.exactBase;
118 }
119
120 if (input.prefixBase !== undefined && value.startsWith(query)) {
121 return input.prefixBase + penalty;
122 }
123
124 if (input.boundaryBase !== undefined) {
125 const boundaryIndex = findBoundaryMatchIndex(
126 value,
127 query,
128 input.boundaryMarkers ?? [" ", "-", "_", "/"],
129 );
130 if (boundaryIndex !== null) {
131 return input.boundaryBase + (ignorePosition ? 0 : boundaryIndex * 2) + penalty;
132 }
133 }
134
135 if (input.includesBase !== undefined) {
136 const includesIndex = value.indexOf(query);
137 if (includesIndex !== -1) {
138 return input.includesBase + (ignorePosition ? 0 : includesIndex * 2) + penalty;
139 }
140 }
141
142 if (input.fuzzyBase !== undefined) {
143 const fuzzyScore = scoreSubsequenceMatch(value, query, { ignorePosition });
144 if (fuzzyScore !== null) {
145 return input.fuzzyBase + fuzzyScore;
146 }
147 }
148
149 return null;
150}
151
152function compareRankedSearchResults<T>(
153 left: RankedSearchResult<T>,
154 right: RankedSearchResult<T>,
155): number {
156 const scoreDelta = left.score - right.score;
157 if (scoreDelta !== 0) return scoreDelta;
158 return left.tieBreaker.localeCompare(right.tieBreaker);
159}
160
161function findInsertionIndex<T>(
162 rankedEntries: RankedSearchResult<T>[],
163 candidate: RankedSearchResult<T>,
164): number {
165 let low = 0;
166 let high = rankedEntries.length;
167
168 while (low < high) {
169 const middle = low + Math.floor((high - low) / 2);
170 const current = rankedEntries[middle];
171 if (!current) {
172 break;
173 }
174
175 if (compareRankedSearchResults(candidate, current) < 0) {
176 high = middle;
177 } else {
178 low = middle + 1;
179 }
180 }
181
182 return low;
183}
184
185export function insertRankedSearchResult<T>(
186 rankedEntries: RankedSearchResult<T>[],
187 candidate: RankedSearchResult<T>,
188 limit: number,
189): void {
190 if (limit <= 0) {
191 return;
192 }
193
194 const insertionIndex = findInsertionIndex(rankedEntries, candidate);
195 if (rankedEntries.length < limit) {
196 rankedEntries.splice(insertionIndex, 0, candidate);
197 return;
198 }
199
200 if (insertionIndex >= limit) {
201 return;
202 }
203
204 rankedEntries.splice(insertionIndex, 0, candidate);
205 rankedEntries.pop();
206}