forked from knaxus/problem-solving-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
44 lines (40 loc) · 1.14 KB
/
index.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
/**
* Evaluation of Postfix Expression
* Input:456*+
* Output:34
*/
const Stack = require('../index');
function evaluatePostfixExpression(expression) {
let s = new Stack();
for (let i = 0; i < expression.length; i++) {
const char = expression[i];
if (!isNaN(char)) {
//if number push the char onto stack
s.push(Number(char));
} else {
// if char is an operator then pop two elements from stack, evaluate them accordingly based on operator.
//push the result to stack
let val1 = s.pop();
let val2 = s.pop();
switch (char) {
case '+':
s.push(val2 + val1);
break;
case '-':
s.push(val2 - val1);
break;
case '*':
s.push(val2 * val1);
break;
case '/':
s.push(val2 / val1);
break;
}
}
}
//pop the value of postfix expression
return s.pop();
}
module.exports = {
evaluatePostfixExpression,
};