|
6 | 6 | * @returns {number|null} - Result of the expression evaluation, or null if the expression is invalid. |
7 | 7 | */ |
8 | 8 | function evaluatePostfixExpression(expression) { |
9 | | - const stack = []; |
| 9 | + const stack = [] |
10 | 10 |
|
11 | 11 | // Helper function to perform an operation and push the result to the stack. Returns success. |
12 | 12 | function performOperation(operator) { |
13 | | - const rightOp = stack.pop(); // Right operand is the top of the stack |
14 | | - const leftOp = stack.pop(); // Left operand is the next item on the stack |
| 13 | + const rightOp = stack.pop() // Right operand is the top of the stack |
| 14 | + const leftOp = stack.pop() // Left operand is the next item on the stack |
15 | 15 |
|
16 | 16 | if (leftOp === undefined || rightOp === undefined) { |
17 | | - return false; // Invalid expression |
| 17 | + return false // Invalid expression |
18 | 18 | } |
19 | 19 | switch (operator) { |
20 | 20 | case '+': |
21 | | - stack.push(leftOp + rightOp); |
22 | | - break; |
| 21 | + stack.push(leftOp + rightOp) |
| 22 | + break |
23 | 23 | case '-': |
24 | | - stack.push(leftOp - rightOp); |
25 | | - break; |
| 24 | + stack.push(leftOp - rightOp) |
| 25 | + break |
26 | 26 | case '*': |
27 | | - stack.push(leftOp * rightOp); |
28 | | - break; |
| 27 | + stack.push(leftOp * rightOp) |
| 28 | + break |
29 | 29 | case '/': |
30 | 30 | if (rightOp === 0) { |
31 | | - return false; |
| 31 | + return false |
32 | 32 | } |
33 | | - stack.push(leftOp / rightOp); |
34 | | - break; |
| 33 | + stack.push(leftOp / rightOp) |
| 34 | + break |
35 | 35 | default: |
36 | | - return false; // Unknown operator |
| 36 | + return false // Unknown operator |
37 | 37 | } |
38 | | - return true; |
| 38 | + return true |
39 | 39 | } |
40 | 40 |
|
41 | | - const tokens = expression.split(/\s+/); |
| 41 | + const tokens = expression.split(/\s+/) |
42 | 42 |
|
43 | 43 | for (const token of tokens) { |
44 | 44 | if (!isNaN(parseFloat(token))) { |
45 | 45 | // If the token is a number, push it to the stack |
46 | | - stack.push(parseFloat(token)); |
| 46 | + stack.push(parseFloat(token)) |
47 | 47 | } else { |
48 | 48 | // If the token is an operator, perform the operation |
49 | 49 | if (!performOperation(token)) { |
50 | | - return null; // Invalid expression |
| 50 | + return null // Invalid expression |
51 | 51 | } |
52 | 52 | } |
53 | 53 | } |
54 | 54 |
|
55 | | - return (stack.length === 1) ? stack[0] : null; |
| 55 | + return stack.length === 1 ? stack[0] : null |
56 | 56 | } |
57 | 57 |
|
58 | | -export { evaluatePostfixExpression }; |
| 58 | +export { evaluatePostfixExpression } |
0 commit comments