Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

searchRanking.ts

200 lines4.7 KB

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();
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;
60​
61function lengthPenalty(value: string, query: string): number {
62 return Math.min(64, Math.max(0, value.length - query.length));
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;
86​
87/**
88 * **Expects pre-normalized inputs**: both `value` and `query` must already be
89 * trimmed and lowercased (e.g. via {@link normalizeSearchQuery}).
90 */
91export function scoreQueryMatch(input: {
92 value: string;
93 query: string;
94 exactBase: number;
95 prefixBase?: number;
96 boundaryBase?: number;
97 includesBase?: number;
98 fuzzyBase?: number;
99 boundaryMarkers?: readonly string[];
100 ignorePosition?: boolean;
101}): number | null {
102 const { value, query } = input;
103 const ignorePosition = input.ignorePosition === true;
104 const penalty = ignorePosition ? 0 : lengthPenalty(value, query);
105​
106 if (!value || !query) {
107 return null;
108 }
109​
110 if (value === query) {
111 return input.exactBase;
112 }
113​
114 if (input.prefixBase !== undefined && value.startsWith(query)) {
115 return input.prefixBase + penalty;
116 }
117​
118 if (input.boundaryBase !== undefined) {
119 const boundaryIndex = findBoundaryMatchIndex(
120 value,
121 query,
122 input.boundaryMarkers ?? [" ", "-", "_", "/"],
123 );
124 if (boundaryIndex !== null) {
125 return input.boundaryBase + (ignorePosition ? 0 : boundaryIndex * 2) + penalty;
126 }
127 }
128​
129 if (input.includesBase !== undefined) {
130 const includesIndex = value.indexOf(query);
131 if (includesIndex !== -1) {
132 return input.includesBase + (ignorePosition ? 0 : includesIndex * 2) + penalty;
133 }
134 }
135​
136 if (input.fuzzyBase !== undefined) {
137 const fuzzyScore = scoreSubsequenceMatch(value, query, { ignorePosition });
138 if (fuzzyScore !== null) {
139 return input.fuzzyBase + fuzzyScore;
140 }
141 }
142​
143 return null;
145​
146function compareRankedSearchResults<T>(
147 left: RankedSearchResult<T>,
148 right: RankedSearchResult<T>,
149): number {
150 const scoreDelta = left.score - right.score;
151 if (scoreDelta !== 0) return scoreDelta;
152 return left.tieBreaker.localeCompare(right.tieBreaker);
154​
155function findInsertionIndex<T>(
156 rankedEntries: RankedSearchResult<T>[],
157 candidate: RankedSearchResult<T>,
158): number {
159 let low = 0;
160 let high = rankedEntries.length;
161​
162 while (low < high) {
163 const middle = low + Math.floor((high - low) / 2);
164 const current = rankedEntries[middle];
165 if (!current) {
166 break;
167 }
168​
169 if (compareRankedSearchResults(candidate, current) < 0) {
170 high = middle;
171 } else {
172 low = middle + 1;
173 }
174 }
175​
176 return low;
178​
179export function insertRankedSearchResult<T>(
180 rankedEntries: RankedSearchResult<T>[],
181 candidate: RankedSearchResult<T>,
182 limit: number,
183): void {
184 if (limit <= 0) {
185 return;
186 }
187​
188 const insertionIndex = findInsertionIndex(rankedEntries, candidate);
189 if (rankedEntries.length < limit) {
190 rankedEntries.splice(insertionIndex, 0, candidate);
191 return;
192 }
193​
194 if (insertionIndex >= limit) {
195 return;
196 }
197​
198 rankedEntries.splice(insertionIndex, 0, candidate);
199 rankedEntries.pop();