JSFiddle - React, Tailwind, and code Playground

by Terrance Smith

JavaScript

var Calculator = function (cn, eq) {
    this.currNumberCtl = cn;
    this.eqCtl = eq;
};

Calculator.prototype = function () {
    var operator = null,
        operatorSet = false,
        equalsPressed = false,
        lastNumber = null,

        add = function (x, y) {
            return x + y;
        },

        subtract = function (x, y) {
            return x - y;
        },

        multiply = function (x, y) {
            return x * y;
        },

        divide = function (x, y) {
            if (y === 0) {
                alert("Can't divide by 0");
            }
            return x / y;
        },

        setVal = function (val, thisObj) {
            thisObj.currNumberCtl.innerHTML = val;
        },

        setEquation = function (val, thisObj) {
            thisObj.eqCtl.innerHTML = val;
        },

        clearNumbers = function () {
            lastNumber = null;
            equalsPressed = operatorSet = false;
            setVal('0', this);
            setEquation('', this);
        },

        setOperator = function (newOperator) {
            if (newOperator == '=') {
                equalsPressed = true;
                calculate(this);
                setEquation('', this);
                return;
            }

            //Handle case where = was pressed
            //followed by an operator (+, -, *, /)
            if (!equalsPressed) calculate(this);
            equalsPressed = false;
            operator = newOperator;
            operatorSet = true;
            lastNumber = parseFloat(this.currNumberCtl.innerHTML);
            var eqText = (this.eqCtl.innerHTML === '') ? lastNumber + ' ' + operator + ' ' : this.eqCtl.innerHTML + ' ' + operator + ' ';
            setEquation(eqText, this);
        },

        numberClick = function (e) {
            var button = (e.target) ? e.target : e.srcElement;
            if (operatorSet === true || this.currNumberCtl.innerHTML === '0') {
                setVal('', this);
               ...