DEV Community

Ivy-Walobwa
Ivy-Walobwa

Posted on

Stack: PostFix Calculator

Postfix Arithmetic

Postfix arithmetic means that the operator goes after the two numbers. Example; 6 * 7 becomes 6 7 *. A postfix expression can be an operand in another postfix expression: 6 7 * 1 - is equivalent to (6 * 7 ) - 1.

Using the stack class in 'stack:array as storage', we will evaluate a postfix expression.

Postfix pseudocode

foreach token 
    if token is integer 
        push token
    else if token is operator
        pop right side value
        pop left side value
        evaluate operator
        push result
next 
Enter fullscreen mode Exit fullscreen mode

Postfix Calculator

function postFixCalc(expression) {
    //create new stack
    let stack = new Stack();

    //loop through each character in provided expression
    for (let idx = 0; idx < expression.length; idx++) {
        //store each character
        let token = expression[idx];

        //if it's a number, push to stack
        //else pop right side and left side, perform operation and push to stack
        if (!isNaN(token)) {
            stack.push(Number(token));
        } else {
            let rhs = stack.pop();
            let lhs = stack.pop();
            //if right or left side is not available
            if (rhs === "UnderFlow" || lhs === "UnderFlow" ) {
                return "Can't perform postfix calculation";
            }
            switch (token) {
                case '+':
                    stack.push(lhs + rhs);
                    break;
                case '-':
                    stack.push(lhs - rhs);
                    break;
                case '*':
                    stack.push(lhs * rhs);
                    break;
                case '/':
                    stack.push(lhs / rhs);
                    break;
                case '%':
                    stack.push(lhs % rhs);
                    break;
            }
        }

    };
   //return result of calculation
    return stack.pop();
}
Enter fullscreen mode Exit fullscreen mode

Sample test code

console.log(postFixCalc('567*+1-'))
Enter fullscreen mode Exit fullscreen mode

The result should be 46 😄.
Thank you for reading!

Top comments (0)