-
Notifications
You must be signed in to change notification settings - Fork 294
/
Copy pathPostFix_Evaluation.js
56 lines (47 loc) · 1.49 KB
/
PostFix_Evaluation.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
function evaluatePostfixExpression(expression) {
const stack = [];
for (const token of expression.split(' ')) {
if (isNumeric(token)) {
stack.push(parseFloat(token));
} else if (isOperator(token)) {
if (stack.length < 2) {
throw new Error('Not enough operands for operator ' + token);
}
const operand2 = stack.pop();
const operand1 = stack.pop();
switch (token) {
case '+':
stack.push(operand1 + operand2);
break;
case '-':
stack.push(operand1 - operand2);
break;
case '*':
stack.push(operand1 * operand2);
break;
case '/':
if (operand2 === 0) {
throw new Error('Division by zero');
}
stack.push(operand1 / operand2);
break;
default:
throw new Error('Invalid operator: ' + token);
}
}
}
if (stack.length === 1) {
return stack[0];
} else {
throw new Error('Invalid expression');
}
}
function isNumeric(token) {
return !isNaN(parseFloat(token)) && isFinite(token);
}
function isOperator(token) {
return token === '+' || token === '-' || token === '*' || token === '/';
}
const postfixExpression = "4 5 5 / +";
const result = evaluatePostfixExpression(postfixExpression);
console.log(`Result of postfix expression "${postfixExpression}" is: ${result}`);