JSFiddle - React, Tailwind, and code Playground

by thor

HTML

<h2>Expression</h2>
<input id="expression" type="text" value=""/>
<input type="submit" id="calculate" value="Calculate"/>
<h2>Result</h2>
<h2 id="result">
</h2>

CSS

h2{
    font-size: 24px;
}

JavaScript

var PolishCalculator = function(expression) {
    var self = this;
    self.numbers = [];
    self.ops = [];
    self.cache = [];
    expression.split(" ").reverse().forEach(function(el, i) {
        if (el == '+' || el == '-' || el == '/' || el == '*') {
            self.ops.push(el);
        }
        else if (!isNaN(el)) {
            self.numbers.push(parseInt(el));
        }
    });
};
PolishCalculator.prototype.reduce = function() {
    var result = 0;
    while (this.numbers.length >= 2 && this.ops.length >= 1) {
        var value = this.calculate(this.numbers, this.ops.pop());
        this.cache.push(value);
        if (this.cache.length >= 2) {
            this.numbers.push(this.cache.pop());
            this.numbers.push(this.cache.pop());
        }
    }
    if (this.cache.length > 1) {
        return NaN;
    }
    else {
        result = this.cache.pop();
    }
    return result;
};
PolishCalculator.prototype.calculate = function(array, op) {
    var a = array.pop();
    var b = array.pop();
    switch (op) {
    case '+':
        return a + b;
    case '-':
        return a - b;
    case '/':
        return a / b;
    case '*':
        return a * b;
    }
};
$(function() {
    $("#calculate").click(function() {
        var expression = $("#expression").val();
        console.log(expression);
        var p = new PolishCalculator(expression);
        var result = p.reduce();
        $("#result").text(result);
    });
});