-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path02-Evaluation-Of-Postfix-Expression.js
44 lines (34 loc) · 1.09 KB
/
02-Evaluation-Of-Postfix-Expression.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
const Stack = require('./stack/Stack');
// Performs Postfix Evaluation on a given exp
function postFixEvaluation (exp) {
for (let i = 0; i < exp.length; i++) {
const c = exp[i];
if (!isNaN(c)) { Stack.push(c - '0'); } else {
const val1 = Stack.pop();
const val2 = Stack.pop();
if (val1 == 'Underflow' || val2 == 'Underflow') {
return "Can't perform postfix evaluation";
}
switch (c) {
case '+':
Stack.push(val2 + val1);
break;
case '-':
Stack.push(val2 - val1);
break;
case '/':
Stack.push(val2 / val1);
break;
case '*':
Stack.push(val2 * val1);
break;
}
}
}
return Stack.pop();
}
// calling the above method
// returns 9
console.log(postFixEvaluation('235*+8-'));
// returns postfix evaluation can't be performed
console.log(postFixEvaluation('23*+'));