-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathseacher.ts
executable file
·64 lines (55 loc) · 1.76 KB
/
seacher.ts
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
export interface SearchOptions<T> {
data: T[];
keyCheck: (keyof T)[];
query: string;
custom?: [RegExp, (value: T, match: string) => boolean][];
}
export function getSearchResults<T extends object>(
options: SearchOptions<T>
): T[] {
if (options.query.trim().length === 0) return options.data;
let queries: [string, string][] = [];
while (options.query.match(/[a-z]+=[^\s]+/)) {
let match = options.query.match(/([a-z]+)=([^\s]+)/) as string[];
options.query = options.query.replace(/[a-z]+=[^\s]+/, "");
queries.push([match[1], match[2]]);
}
const check = (k: keyof T, v: string, d: T) => {
if (v.length === 0) return;
switch (typeof d[k]) {
case "string": {
try {
const regex = new RegExp(v, "gi");
return (d[k] as string).match(regex);
} catch {
return (d[k] as string).includes(v.toLowerCase());
}
}
case "number": {
return (d[k] as number) === parseInt(v);
}
case "boolean": {
return (d[k] as boolean) === (v.toLowerCase() === "true");
}
}
return false;
};
const customChecks: string[] = [];
console.log(options.custom);
for (const regex of options.custom ?? []) {
console.log(options.query, regex);
while (options.query.match(regex[0])) {
let match = options.query.match(regex[0])?.[1];
options.query = options.query.replace(regex[0], "");
customChecks.push(match as string);
}
}
console.log(customChecks);
const filtered = options.data.filter(
(d) =>
queries.some((x) => check(x[0] as keyof T, x[1], d)) ||
options.keyCheck.some((x) => check(x, options.query.trim(), d)) ||
options.custom?.some((x) => customChecks.some((y) => x[1](d, y)))
);
return filtered;
}