JSFiddle - React, Tailwind, and code Playground

by Darby Rathbone

JavaScript

Math.add = function (a, b) {
    return a + b;
};
Math.sub = function (a, b) {
    return a - b;
};
Math.mult = function (a, b) {
    return a * b;
};
Math.div = function (a, b) {
    return a / b;
};
var expression = "",
    rNumbers = "(\\-*?[0-9\\.]+)",
    rParens = new RegExp("\\(([^\\(\\)]+)\\)"),
    rAdd = new RegExp(rNumbers + "\\+" + rNumbers ),
    rSubtract = new RegExp(rNumbers + "\\-" + rNumbers),
    rMultiply = new RegExp(rNumbers + "\\*" + rNumbers),
    rDivide = new RegExp(rNumbers + "\\/" + rNumbers),
    rExponent = new RegExp(rNumbers + "\\^" + rNumbers),
    evaluate = function (e) {
        console.dir(arguments);
        e=e.replace(rParens, function (a1, a2) {
            return evaluate(a2);
        });
        while (rExponent.test(e)) {
            e= e.replace(rExponent, function (a1, a2, a3) {
                console.dir(arguments);
                return Math.pow(parseFloat(a2), parseFloat(a3));
            });
        }
        while (rMultiply.test(e) || rDivide.test(e)) {
            e=e.replace(rMultiply, function (a1, a2, a3) {
                console.dir(arguments);
                return Math.mult(parseFloat(a2), parseFloat(a3));
            });
            e=e.replace(rDivide, function (a1, a2, a3) {
                console.dir(arguments);
                return Math.div(parseFloat(a2), parseFloat(a3));
            });
        }
        while (rAdd.test(e) || rSubtract.test(e)) {
            e=e.replace(rAdd, function (a1, a2, a3) {
                console.dir(arguments);
                return Math.add(parseFloat(a2), parseFloat(a3));
            });
            e=e.replace(rSubtract, function (a1, a2, a3) {
                console.dir(arguments);
                return Math.sub(parseFloat(a2), parseFloat(a3));
            });
        }
        return e;
    };
console.log(evaluate(expression));