-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathchar-class.ts
87 lines (76 loc) · 2.28 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import type { CharacterClass, CharacterEscape, EncodedRegex } from '../types';
import { ensureText } from '../utils';
/**
* Creates a character class which matches any one of the given characters.
*
* @param elements - Member characters or character ranges.
* @returns Character class.
*/
export function charClass(...elements: Array<CharacterClass | CharacterEscape>): CharacterClass {
if (!elements.length) {
throw new Error('Expected at least one element');
}
return {
elements: elements.map((c) => c.elements).flat(),
encode: encodeCharClass,
};
}
/**
* Creates a character class which matches any one of the characters in the range.
*
* @param start - Start of the range (single character).
* @param end - End of the range (single character).
* @returns Character class.
*/
export function charRange(start: string, end: string): CharacterClass {
if (start.length !== 1 || end.length !== 1) {
throw new Error(`Expected single characters, but received "${start}" & "${end}"`);
}
if (start > end) {
[start, end] = [end, start];
}
return {
elements: [`${start}-${end}`],
encode: encodeCharClass,
};
}
/**
* Creates a character class which matches any one of the given characters.
*
* @param chars - Characters to match.
* @returns Character class.
*/
export function anyOf(chars: string): CharacterClass {
ensureText(chars);
return {
elements: chars.split('').map(escapeChar),
encode: encodeCharClass,
};
}
/**
* Creates a negated character class which matches any character that is not in the given character class.
*
* @param element - Character class or character escape to negate.
* @returns Negated character class.
*/
export function negated(element: CharacterClass | CharacterEscape): EncodedRegex {
return encodeCharClass.call(element, true);
}
/**
* @deprecated Renamed to `negated`.
*/
export const inverted = negated;
/** Escape chars for usage inside char class */
function escapeChar(text: string): string {
// anyOf(']-\\^')
return text.replace(/[\]\-\\^]/g, '\\$&'); // "$&" is whole matched string
}
function encodeCharClass(
this: CharacterClass | CharacterEscape,
isNegated?: boolean,
): EncodedRegex {
return {
precedence: 'atom',
pattern: `[${isNegated ? '^' : ''}${this.elements.join('')}]`,
};
}