-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathchar-class.ts
57 lines (45 loc) · 1.48 KB
/
char-class.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
import { encodeCharClass } from '../encoder';
import type { CharacterClass, CharacterEscape, EncodedRegex } from '../types';
export function charClass(...elements: Array<CharacterClass | CharacterEscape>): CharacterClass {
if (!elements.length) {
throw new Error('`charClass` should receive at least one element');
}
return {
chars: elements.map((c) => c.chars).flat(),
ranges: elements.map((c) => c.ranges ?? []).flat(),
};
}
export function charRange(start: string, end: string): CharacterClass {
if (start.length !== 1) {
throw new Error('`charRange` should receive only single character `start` string');
}
if (end.length !== 1) {
throw new Error('`charRange` should receive only single character `end` string');
}
if (start > end) {
throw new Error('`start` should be before or equal to `end`');
}
return {
chars: [],
ranges: [{ start, end }],
};
}
export function anyOf(characters: string): CharacterClass {
const chars = characters.split('').map((c) => escapeCharClass(c));
if (chars.length === 0) {
throw new Error('`anyOf` should received at least one character');
}
return {
chars,
};
}
export function negated(element: CharacterClass | CharacterEscape): EncodedRegex {
return encodeCharClass(element, true);
}
/**
* @deprecated Renamed to `negated`.
*/
export const inverted = negated;
function escapeCharClass(text: string): string {
return text.replace(/[\]\\]/g, '\\$&'); // $& means the whole matched string
}