-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbalance.parantheses.js
86 lines (73 loc) · 1.89 KB
/
balance.parantheses.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
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
82
83
84
85
86
var expression = 'a+b*c+(d+e)*f';
var characters = expression.split('');
var output = [];
var operators = [];
function peek(stack) {
return (stack.length > 0) ? stack[stack.length - 1] : undefined;
}
function isOperator(character) {
return character === '+' || character === '*';
}
var precedences = {
'+': 1,
'*': 2
};
function pushOperator(operator) {
const rightOperand = output.pop();
const leftOperand = output.pop();
output.push({
left: leftOperand,
right: rightOperand,
op: operator
});
}
function pushOperand(operand) {
output.push(operand);
}
characters.forEach(character => {
if (isOperator(character)) {
let currentOperator = character;
let topOperator = peek(operators);
while (!!topOperator && topOperator !== '(' && (precedences[topOperator] >= precedences[currentOperator])) {
pushOperator(topOperator);
operators.pop();
topOperator = peek(operators);
}
operators.push(currentOperator);
} else if (character === ')') {
let topOperator = peek(operators);
while (!!topOperator && topOperator !== '(') {
pushOperator(topOperator);
operators.pop();
topOperator = peek(operators);
}
if (topOperator === '(') {
operators.pop();
}
} else if (character === '(') {
operators.push(character);
} else {
pushOperand(character);
}
});
while (operators.length > 0) {
pushOperator(operators.pop());
}
// Abstract Syntax Tree representation of the expression
var ast = output.pop();
//abc*+de+f*+
console.log('output = ', JSON.stringify(ast, null, 2));
function isTree(node) {
return node.op !== undefined;
}
function toInfixForm(ast) {
if (isTree(ast)) {
const { left, right, op } = ast;
return `(${toInfixForm(left)}${op}${toInfixForm(right)})`;
} else {
return ast;
}
}
//a+b*c+(d+e)*f
//((a+(b*c))+((d+e)*f))
console.log('with parentheses = ', toInfixForm(ast));