-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathchoice-of.ts
35 lines (30 loc) · 980 Bytes
/
choice-of.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
import { encodeSequence } from '../encoder/encoder';
import type { EncodeOutput } from '../encoder/types';
import { asNodeArray } from '../utils/nodes';
import type { RegexElement, RegexNode } from '../types';
export interface ChoiceOf extends RegexElement {
type: 'choiceOf';
alternatives: RegexNode[][];
}
export function choiceOf(
...alternatives: Array<RegexNode | RegexNode[]>
): ChoiceOf {
if (alternatives.length === 0) {
throw new Error('`choiceOf` should receive at least one alternative');
}
return {
type: 'choiceOf',
alternatives: alternatives.map((c) => asNodeArray(c)),
encode: encodeChoiceOf,
};
}
function encodeChoiceOf(this: ChoiceOf): EncodeOutput {
const encodedAlternatives = this.alternatives.map((c) => encodeSequence(c));
if (encodedAlternatives.length === 1) {
return encodedAlternatives[0]!;
}
return {
precedence: 'alternation',
pattern: encodedAlternatives.map((n) => n.pattern).join('|'),
};
}