-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathtext-matching.ts
More file actions
79 lines (73 loc) · 2.47 KB
/
Copy pathtext-matching.ts
File metadata and controls
79 lines (73 loc) · 2.47 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { NormalizerOptions, normalizeTextForSearch } from './text-normalization'
export type { NormalizerOptions } from './text-normalization'
/**
* Store info about where did we found the pattern inside the corpus
*/
export interface PositiveMatchInfo {
startPos: number
endPos: number
}
export const NO_MATCH = 'NO_MATCH'
export type MatchInfo = PositiveMatchInfo | typeof NO_MATCH
/**
* Identify pattern matches within a corpus, also considering normalization
*
* If there is no match, an empty array is returned.
*
* NOTE: depending on normalization options, the string length can change,
* and in that case, match position can be incorrect.
*/
export const findTextMatches = (
rawCorpus: string | null | undefined,
pattern: (string | undefined)[],
options: NormalizerOptions = {},
): PositiveMatchInfo[] => {
const normalizedCorpus = normalizeTextForSearch(rawCorpus || '', options)
const matches: PositiveMatchInfo[] = pattern
.filter((s): s is string => !!s)
.map(rawPattern => {
const normalizedPattern = normalizeTextForSearch(rawPattern!, options)
const matchStart = normalizedCorpus.indexOf(normalizedPattern)
return matchStart !== -1
? {
startPos: matchStart,
endPos: matchStart + rawPattern.length,
}
: 'NO_MATCH'
})
.filter((m): m is PositiveMatchInfo => m !== NO_MATCH)
return matches
}
/**
* Identify the first pattern match within a corpus, also considering normalization
*
* If there is no match, NO_MATCH is returned.
*
* NOTE: depending on normalization options, the string length can change,
* and in that case, match position can be incorrect.
*/
export const findTextMatch = (
rawCorpus: string | null | undefined,
search: (string | undefined)[],
options: NormalizerOptions = {},
): MatchInfo => {
const matches = findTextMatches(rawCorpus, search, options)
return matches[0] ?? NO_MATCH
}
/**
* Check if all patterns match within a corpus, also considering normalization
*
* NOTE: depending on normalization options, the string length can change,
* and in that case, match position can be incorrect.
*
* Also NOTE: if there are no patterns given, the result will be true.
*
*/
export const hasTextMatchesForAll = (
rawCorpus: string | null | undefined,
patterns: (string | undefined)[],
options: NormalizerOptions = {},
): boolean =>
patterns
.filter(pattern => !!pattern)
.every(pattern => findTextMatch(rawCorpus, [pattern], options) !== NO_MATCH)