UNPKG

2.74 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.reconstruct = void 0;
4const types_1 = require("./types");
5const write_set_tokens_1 = require("./write-set-tokens");
6const reduceStack = (stack) => stack.map(exports.reconstruct).join('');
7const createAlternate = (token) => {
8 if ('options' in token) {
9 return token.options.map(reduceStack).join('|');
10 }
11 else if ('stack' in token) {
12 return reduceStack(token.stack);
13 }
14 else {
15 throw new Error(`options or stack must be Root or Group token`);
16 }
17};
18exports.reconstruct = (token) => {
19 switch (token.type) {
20 case types_1.types.ROOT:
21 return createAlternate(token);
22 case types_1.types.CHAR: {
23 const c = String.fromCharCode(token.value);
24 // Note that the escaping for characters inside classes is handled
25 // in the write-set-tokens module so '-' and ']' are not escaped here
26 return (/[[\\{}$^.|?*+()]/.test(c) ? '\\' : '') + c;
27 }
28 case types_1.types.POSITION:
29 if (token.value === '^' || token.value === '$') {
30 return token.value;
31 }
32 else {
33 return `\\${token.value}`;
34 }
35 case types_1.types.REFERENCE:
36 return `\\${token.value}`;
37 case types_1.types.SET:
38 return write_set_tokens_1.writeSetTokens(token);
39 case types_1.types.GROUP: {
40 // Check token.remember
41 const prefix = token.remember ? '' :
42 token.followedBy ? '?=' :
43 token.notFollowedBy ? '?!' :
44 '?:';
45 return `(${prefix}${createAlternate(token)})`;
46 }
47 case types_1.types.REPETITION: {
48 const { min, max } = token;
49 let endWith;
50 if (min === 0 && max === 1) {
51 endWith = '?';
52 }
53 else if (min === 1 && max === Infinity) {
54 endWith = '+';
55 }
56 else if (min === 0 && max === Infinity) {
57 endWith = '*';
58 }
59 else if (max === Infinity) {
60 endWith = `{${min},}`;
61 }
62 else if (min === max) {
63 endWith = `{${min}}`;
64 }
65 else {
66 endWith = `{${min},${max}}`;
67 }
68 return `${exports.reconstruct(token.value)}${endWith}`;
69 }
70 case types_1.types.RANGE:
71 return `${write_set_tokens_1.setChar(token.from)}-${write_set_tokens_1.setChar(token.to)}`;
72 default:
73 throw new Error(`Invalid token type ${token}`);
74 }
75};
76//# sourceMappingURL=reconstruct.js.map
\No newline at end of file