-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparser.ts
81 lines (69 loc) · 1.7 KB
/
parser.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
/**
* Inserts a '.' wherever there needs to be a concat operation
* @param exp string
* @returns string with concat inserted
*/
export const insertConcatOperator = (exp: string): string => {
let output = "";
for (let i = 0; i < exp.length; i++) {
const token = exp[i];
output = output + token;
if (token === "(" || token === "|") {
continue;
}
if (i < exp.length - 1) {
let lookahead = exp[i + 1];
if (lookahead === "*" || lookahead === "|" || lookahead === ")") {
continue;
}
output = output + ".";
}
}
return output;
};
const peek = (stack: any[]) => {
return stack.length && stack[stack.length - 1];
};
const operatorPrecedence = {
"|": 0,
".": 1,
"*": 2,
};
/**
* Converts an expression into postfix
* @param exp string
* @returns string in postfix order
*/
export const toPostFix = (exp: string) => {
let output = "";
const operatorStack = [];
for (const token of exp) {
if (token === "." || token === "|" || token === "*") {
while (
operatorStack.length &&
peek(operatorStack) !== "(" &&
operatorPrecedence[
peek(operatorStack) as keyof typeof operatorPrecedence
] >= 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;
};