-
Notifications
You must be signed in to change notification settings - Fork 274
/
Copy pathmatches.ts
47 lines (42 loc) · 1.29 KB
/
matches.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
export type NormalizerFn = (textToNormalize: string) => string;
export type TextMatch = string | RegExp;
export type TextMatchOptions = {
exact?: boolean;
normalizer?: NormalizerFn;
};
export function matches(
matcher: TextMatch,
text: string | undefined,
normalizer: NormalizerFn = getDefaultNormalizer(),
exact: boolean = true,
): boolean {
if (typeof text !== 'string') {
return false;
}
const normalizedText = normalizer(text);
if (typeof matcher === 'string') {
const normalizedMatcher = normalizer(matcher);
return exact
? normalizedText === normalizedMatcher
: normalizedText.toLowerCase().includes(normalizedMatcher.toLowerCase());
} else {
// Reset state for global regexes: https://stackoverflow.com/a/1520839/484499
matcher.lastIndex = 0;
return matcher.test(normalizedText);
}
}
type NormalizerConfig = {
trim?: boolean;
collapseWhitespace?: boolean;
};
export function getDefaultNormalizer({
trim = true,
collapseWhitespace = true,
}: NormalizerConfig = {}): NormalizerFn {
return (text: string) => {
let normalizedText = text;
normalizedText = trim ? normalizedText.trim() : normalizedText;
normalizedText = collapseWhitespace ? normalizedText.replace(/\s+/g, ' ') : normalizedText;
return normalizedText;
};
}