-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrepeat.ts
36 lines (32 loc) · 1.08 KB
/
repeat.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
import { encodeAtomic } from '../encoder';
import type { EncodedRegex, RegexSequence } from '../types';
import { ensureElements } from '../utils';
/**
* Options for the `repeat` function.
*
* @param min - Minimum number of times to match.
* @param max - Maximum number of times to match (default: unlimited).
* @param greedy - Whether to use greedy quantifiers (default: true).
*/
export type RepeatOptions = number | { min: number; max?: number; greedy?: boolean };
/**
* Creates a quantifier which matches the given sequence a specific number of times.
*
* @param sequence - Sequence to match.
* @param options - Quantifier options.
*/
export function repeat(sequence: RegexSequence, options: RepeatOptions): EncodedRegex {
const elements = ensureElements(sequence);
if (typeof options === 'number') {
return {
precedence: 'sequence',
pattern: `${encodeAtomic(elements)}{${options}}`,
};
}
return {
precedence: 'sequence',
pattern: `${encodeAtomic(elements)}{${options.min},${options?.max ?? ''}}${
options.greedy === false ? '?' : ''
}`,
};
}