-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
postfix.js
40 lines (34 loc) · 1.01 KB
/
postfix.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
function evaluatePostFix(exp) {
let stack = new Stack();
for(let i = 0, length = exp.length; i < length; i++){
if(isNaN(exp[i])){
let op1, op2, operand;
operand = exp[i];
op2 = parseInt(stack.pop());
op1 = parseInt(stack.pop());
if(isNaN(op1) || isNaN(op2)){
return 'invalid expression';
}
switch (operand){
case "+":
stack.push(op1+op2);
break;
case "-":
stack.push(op1-op2);
break;
case "/":
stack.push(op1/op2);
break;
case "*":
stack.push(op1*op2);
break;
default:
return 'invalid expression';
}
}
else {
stack.push(exp[i]);
}
}
return stack.length() === 1 ? stack.peek() : 'invalid expression';
}