Day 1/100 Addendum

Came up with another way to do the RPN calculator by attaching functions in a JavaScript "dictionary":

// jshint esversion: 6

function add(p) {
    return p.x + p.y;
}

function multiply(p) {
    return p.x * p.y;
}

function subtract(p) {
    return p.x - p.y;
}

function divide(p) {
    return p.x / p.y;
}

function calculate(input) {
    let stack = [];
    let operand = {};
    let n = {x: 0, y: 0};
    operand['+'] = add.bind(null, n);
    operand['-'] = subtract.bind(null, n);
    operand['*'] = multiply.bind(null, n);
    operand['/'] = divide.bind(null, n);

    for (let i=0; i < input.length; i++) {
        element = parseFloat(input[i]);
        if (!Number.isNaN(element)) {
            stack.push(element);
        } else {
            if (input[i] in operand) {
                n.y = stack.pop();
                n.x = stack.pop();
                let result = operand[input[i]]();
                stack.push(result);
            }
        }
    }
    return stack;
}

console.log(calculate(['3','4','11', '+', '*', '22', '/','.']));  // 2.04545
console.log(calculate(['2', '2', '+', '.']));  // 4
console.log(calculate(['2', '+', '.']));  // error, too few items on the stack

links

social