~james/core

core/web/src/lib/components/lines/search.ts -rw-r--r-- 862 bytes
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 16 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
export interface LineMatch {
	line: number;
	start: number;
	end: number;
}

export const MATCH_LIMIT = 10_000;

const escapeRegExp = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");

export const findMatches = (
	lines: readonly string[],
	query: string,
	limit = MATCH_LIMIT
): LineMatch[] => {
	const matches: LineMatch[] = [];
	if (query === "") return matches;
	const pattern = new RegExp(escapeRegExp(query), "giu");
	for (let line = 0; line < lines.length; line++) {
		for (const found of lines[line].matchAll(pattern)) {
			matches.push({
				line: line + 1,
				start: found.index,
				end: found.index + found[0].length
			});
			if (matches.length >= limit) return matches;
		}
	}
	return matches;
};

export const wrapIndex = (index: number, length: number): number =>
	length === 0 ? -1 : ((index % length) + length) % length;