-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoRegex.js
48 lines (40 loc) · 1.69 KB
/
toRegex.js
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
import { tokenTypes } from "./tokens.js";
import { wordTypes } from "./words.js";
export function toRegex(parsedTokens) {
let regex = '';
for (let i = 0; i < parsedTokens.length; i++) {
const token = parsedTokens[i];
if (token.type === tokenTypes.WORD.name) {
if(!Object.keys(wordTypes).includes(token.value)) {
throw new Error("Error: " + token.value);
}
for (const word of Object.values(wordTypes)) {
if(token.value === word.name && !word?.prepend) {
regex += word.value || word.openTag || '';
}
}
} else if (token.type === tokenTypes.STRING.name) {
regex += token.value.replace(/[.*+?^${}()|[\]\\\/]/g, "\\$&");
} else if (token.type === tokenTypes.PUNCTUATION.name) {
if (token.value === tokenTypes.PUNCTUATION.openTag) {
regex += tokenTypes.PUNCTUATION.openTag;
} else if (token.value === tokenTypes.PUNCTUATION.closeTag) {
regex += tokenTypes.PUNCTUATION.closeTag;
} else {
throw new Error("Error: " + token.value);
}
}
if (token.children) {
const prependWord = Object.values(wordTypes).find(word => token.value === word.name && word?.prepend);
if(prependWord) {
regex += toRegex(token.children) + (prependWord.value || prependWord.openTag || '');
} else {
regex += toRegex(token.children);
}
}
}
if (parsedTokens[0].value === wordTypes.GROUP.name) {
regex += wordTypes.GROUP.closeTag;
}
return regex;
}