forked from knaxus/problem-solving-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
61 lines (55 loc) · 1.45 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* Evaluation of Postfix Expression
* Input:456*+
* Output:34
*/
const Stack = require('../index');
const ERROR_STRING = 'Expression is not in order';
function evaluatePostfixExpression(expression) {
// eslint-disable-next-line no-param-reassign
expression = expression.trim();
if (expression.length === 0 || expression.length === 1) {
throw new Error(ERROR_STRING);
}
const s = new Stack();
// eslint-disable-next-line no-plusplus
for (let i = 0; i < expression.length; i++) {
const char = expression[i];
// eslint-disable-next-line no-restricted-globals
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
const val1 = s.pop();
const 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;
default:
throw new Error('Operation is not valid');
}
}
}
// pop the value from stack
const result = s.pop();
if (s.isEmpty()) {
return result;
}
throw new Error(ERROR_STRING);
}
module.exports = {
evaluatePostfixExpression,
ERROR_STRING,
};