JSFiddle - React, Tailwind, and code Playground

by Darby Rathbone

JavaScript

var parser = function ( ip ) {
    var nums = /(.*?[^\-\+\*\/\^]+)([\-\+\*\/\^])/gim;
    var order = ["^", '*', '/',
        '-', '+'];
    var actions = {
        "^": function (a, b) {
            return Math.pow(this['num'](a), this['num'](b));
        },
            "*": function (a, b) {
            return (this['num'](a) * this['num'](b));
        },
            "/": function (a, b) {
            return (this['num'](a) / this['num'](b));
        },
            "-": function (a, b) {
            return (this['num'](a) - this['num'](b));
        },
            "+": function (a, b) {
            return (this['num'](a) + this['num'](b));
        },
            "num": function (input) {
            return parseFloat(input.toString().replace(/(\-+)?(.+)/gi, function (m, negatives, number) {

                if (typeof negatives !== 'undefined') return parseFloat((negatives.split('').length % 2 ? '-' : '') + (number));
                else return parseFloat(number);
            }));
        },
            "p": function (input) {
            while (/\(([^\(\)]+)\)/.test(input)) {
                input = input.replace(/\(([^\(\)]+)\)/, function (m, p) {
                    return actions['solve'](p);
                });
            }

            return this['solve'](input);
        },
            "solve": function (input) {
            var a = input.split(nums).filter(Boolean);
            var op = function op(match, a) {
                a.forEach(function (e, i, ar) {
                    if (e == match) {
                        a[i + 1] = actions[e](a[i - 1], a[i + 1]);
                        a[i - 1] = '';
                        a[i] = '';
                    }
                });
                return a;
            };
            order.forEach(function (o) {
                a = op(o, a);
                a = a.filter(Boolean);
            });
            return a[0];
        }
    };
    return actions['p']( ip...