8000 feat: add algorithm to evaluate postfix strings · TheAlgorithms/JavaScript@032b28f · GitHub
[go: up one dir, main page]

Skip to content

Commit 032b28f

Browse files
committed
feat: add algorithm to evaluate postfix strings
1 parent 1de5ab7 commit 032b28f

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/**
2+
* Evaluate a numeric operations string using a stack.
3+
* Supports basic arithmetic operations: +, -, *, /
4+
*
5+
* @param {string} expression - Numeric operations expression to evaluate.
6+
* @returns {number|null} - Result of the expression evaluation, or null if the expression is invalid.
7+
*/
8+
function evaluateExpression(expression) {
9+
const stack = [];
10+
11+
// Helper function to perform an operation and push the result to the stack
12+
function performOperation(operator) {
13+
const operand2 = stack.pop();
14+
const operand1 = stack.pop();
15+
if (operator === '+' || operator === '-' || operator === '*' || operator === '/') {
16+
if (operand1 === undefined || operand2 === undefined) {
17+
return null; // Invalid expression
18+
}
19+
switch (operator) {
20+
case '+':
21+
stack.push(operand1 + operand2);
22+
break;
23+
case '-':
24+
stack.push(operand1 - operand2);
25+
break;
26+
case '*':
27+
stack.push(operand1 * operand2);
28+
break;
29+
case '/':
30+
if (operand2 === 0) {
31+
return null; // Division by zero
32+
}
33+
stack.push(operand1 / operand2);
34+
break;
35+
}
36+
} else {
37+
return null; // Invalid operator
38+
}
39+
}
40+
41+
const tokens = expression.split(' ');
42+
43+
for (const token of tokens) {
44+
if (!isNaN(parseFloat(token))) {
45+
// If the token is a number, push it to the stack
46+
stack.push(parseFloat(token));
47+
} else {
48+
// If the token is an operator, perform the operation
49+
const result = performOperation(token);
50+
if (result === null) {
51+
return null; // Invalid expression
52+
}
53+
}
54+
}
55+
56+
if (stack.length === 1) {
57+
// The final result should be on the stack
58+
return stack[0];
59+
} else {
60+
return null; // Invalid expression
61+
}
62+
}
63+
64+
export { evaluateExpression };
65+

0 commit comments

Comments
 (0)
0