-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.js
More file actions
74 lines (61 loc) · 1.74 KB
/
parser.js
File metadata and controls
74 lines (61 loc) · 1.74 KB
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
function insertExplicitConcatOperator(exp) {
let output = '';
for (let i = 0; i < exp.length; i++) {
const token = exp[i];
output += token;
if (token === '(' || token === '|') {
continue;
}
if (i < exp.length - 1) {
const lookahead = exp[i + 1];
if (lookahead === '*' || lookahead === '?' || lookahead === '+' || lookahead === '|' || lookahead === ')') {
continue;
}
output += '.';
}
}
return output;
};
function peek(stack) {
return stack.length && stack[stack.length - 1];
}
const operatorPrecedence = {
'|': 0,
'.': 1,
'?': 2,
'*': 2,
'+': 2
};
function toPostfix(exp) {
let output = '';
const operatorStack = [];
for (const token of exp) {
//if token is an operator
if (token === '.' || token === '|' || token === '*' || token === '?' || token === '+') {
while (operatorStack.length && peek(operatorStack) !== '('
&& operatorPrecedence[peek(operatorStack)] >= operatorPrecedence[token]) {
output += operatorStack.pop();
}
operatorStack.push(token);
} else if (token === '(' || token === ')') {
if (token === '(') {
operatorStack.push(token);
} else {
while (peek(operatorStack) !== '(') {
output += operatorStack.pop();
}
operatorStack.pop();
}
} else {
output += token;
}
}
while (operatorStack.length) {
output += operatorStack.pop();
}
return output;
};
module.exports = {
toPostfix,
insertExplicitConcatOperator
}