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

searchRanking.ts

204 lines5.0 KB

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