Prefix calculator using stack in JavaScript

A Reverse Polish Notation (RPN) calculator processes operators after their operands, using a stack data structure. This implementation evaluates mathematical expressions efficiently without parentheses.

How RPN Works

In RPN, operators follow their operands. For example, "3 4 +" means "3 + 4". The algorithm uses a stack:

  • Push operands onto the stack

  • When encountering an operator, pop two operands, perform the operation, and push the result back

  • The final stack contains the result

Step-by-Step Process

Consider the input array:

const arr = [1, 5, '+', 6, 3, '-', '/', 7, '*'];

Processing steps:

  1. 1 is an operand, push to stack: [1]

  2. 5 is an operand, push to stack: [1, 5]

  3. '+' is an operator, pop 5 and 1, calculate 1+5=6, push result: [6]

  4. 6 is an operand, push to stack: [6, 6]

  5. 3 is an operand, push to stack: [6, 6, 3]

  6. '-' is an operator, pop 3 and 6, calculate 6-3=3, push result: [6, 3]

  7. '/' is an operator, pop 3 and 6, calculate 6/3=2, push result: [2]

  8. 7 is an operand, push to stack: [2, 7]

  9. '*' is an operator, pop 7 and 2, calculate 2*7=14, push result: [14]

Implementation

const arr = [1, 5, '+', 6, 3, '-', '/', 7, '*'];

const stackCalculator = (arr = []) => {
    const operations = {
        '+': (a, b) => a + b,
        '-': (a, b) => a - b,
        '*': (a, b) => a * b,
        '/': (a, b) => a / b
    };
    
    const stack = [];
    
    arr.forEach(value => {
        if (value in operations) {
            // Pop two operands and apply operation
            const operand2 = stack.pop();
            const operand1 = stack.pop();
            const result = operations[value](operand1, operand2);
            stack.push(result);
        } else {
            // Push operand to stack
            stack.push(value);
        }
    });
    
    return stack[0]; // Return the final result
};

console.log(stackCalculator(arr));
14

Alternative Compact Implementation

const arr = [1, 5, '+', 6, 3, '-', '/', 7, '*'];

const compactCalculator = (arr = []) => {
    const operations = {
        '+': (a, b) => a + b,
        '-': (a, b) => a - b,
        '*': (a, b) => a * b,
        '/': (a, b) => a / b
    };
    
    const stack = [];
    
    arr.forEach(value => {
        stack.push(value in operations
            ? operations[value](...stack.splice(-2))
            : value
        );
    });
    
    return stack[0];
};

console.log(compactCalculator(arr));
14

Testing with Different Expressions

// Test case 1: Simple addition
console.log(stackCalculator([3, 4, '+'])); // 7

// Test case 2: Complex expression: (15 / (7 - (1 + 1))) * 3
console.log(stackCalculator([15, 7, 1, 1, '+', '-', '/', 3, '*'])); // 9

// Test case 3: Multiple operations
console.log(stackCalculator([2, 3, '+', 4, '*', 5, '-'])); // 15
7
9
15

Key Points

  • RPN eliminates the need for parentheses in mathematical expressions

  • Stack-based evaluation processes tokens from left to right

  • Binary operators always pop two operands and push one result

  • The final stack should contain exactly one element: the result

Conclusion

The RPN calculator using a stack provides an efficient way to evaluate mathematical expressions without ambiguity. This approach is commonly used in calculators and programming language interpreters for its simplicity and effectiveness.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements