Preview:
const expression1 = "2 1 + 3 *";

let expression2 = "5 3 6 * + 5 3 / - 7 +"


//alternative fn to distinguish numericals from operators
function isNumeric(num) {
     return !Number.isNaN(parseFloat(num)) && Number.isFinite(num);
 }

// Write a function that takes in a string, which contains a polish notation expression, and evaluates it.

// separate numeric values from operators
// reverse polish notation (RPN) works by putting the nums on the stack, 
// then when it encounters an operator, it works on the previous 2 values, 
// by popping them off the stack, evaluating the expression, 
// and pushing the resulted value back to the stack 


function evaluateRPN(expression) {

    const tokens = expression.split(" "); //split by whitespace

    const stack = [] //initialize empty stack

    // check if its an operator later with include
    const operators = ["+", "-", "/", "*", "^"];


    for (let token of tokens) {
        // debugger; 
        if (operators.includes(token)) {
            
            if (stack.length < 2 ) {
                throw new Error("Invalid RPN expression")
            }
            const a = stack.pop();
            const b = stack.pop();
            
            switch(token) {
                case "+": 
                    stack.push(a+b);
                    break;
                case "-": 
                    stack.push(b-a);
                    break;
                case "*": 
                    stack.push(a*b);
                    break;
                case "/": 
                    stack.push(b/a);
                    break;
        } 
        
    }  else {
        // convert token to number and push to the stack
        stack.push(Number(token))
    } 
        
}
    return stack.pop();
}

downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter