Day 1 / 100: RPN Calculator in JavaScript

Day 1: Decided to play around with a RPN calculator in JavaScript (command-line for now). Right now it reads a pre-parsed array of values (eventually I want to get it so it will take in either string input, or perhaps a simple 4-function graphical calculator. But today I'm starting small.).

Here's the code:

// jshint esversion: 6

function addition(a, b) {
    return a + b;
}

function multiply(a, b) {
    return a * b;
}

function subtract(a, b) {
    return a - b;
}

function divide(a, b) {
    return a / b;
}

function calculate(input) {
    let stack = [];
    for (let i=0; i < input.length; i++) {
        element = parseFloat(input[i]);
        if (!Number.isNaN(element)) {
            stack.push(element);
        } else {
            if (input[i] === '+') {
                let b = stack.pop();
                let a = stack.pop();
                stack.push(addition(a, b));
            }
            if (input[i] === '*') {
                let b = stack.pop();
                let a = stack.pop();
                stack.push(multiply(a, b));
            }
            if (input[i] === '/') {
                let b = stack.pop();
                let a = stack.pop();
                stack.push(divide(a, b));
            }
            if (input[i] === '-') {
                let b = stack.pop();
                let a = stack.pop();
                stack.push(subtract(a, b));
            }
        }
    }
    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