DEV Community

loading...

Stack: PostFix Calculator

ivywalobwa profile image Ivy-Walobwa ・1 min read

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 

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();
}

Sample test code

console.log(postFixCalc('567*+1-'))

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

Discussion (0)

pic
Editor guide