JSFiddle - React, Tailwind, and code Playground

by Darby Rathbone

JavaScript

var paren = function(d) {
  d = "(" + d + ")";
  var c = [], a = 0, b = [];
  return d.split("").filter(function(a) {
    return a.trim();
  }).forEach(function(d) {
    d === ")" && (c.push(b.pop()), a--, b[a] += "#" + (c.length - 1) ), b[a] || (b[a] = ""), 
    b[a] += d, d === "(" && a++;
  }), c.concat(b);
};

var re = /(?:\(\#)(\d+)(?:\))/gi;

var g = paren("1((1+5^2)- 5) / (42 + 8 - (7 × 2))");
document.body.innerHTML += "<br/>"+g.join("<br/>")+"<br/>"+"<br/>";
/**
* Evaluate a mathematical expression (as a string) and return the result
* @param {String} expr A mathematical expression
* @returns {Decimal} Result of the mathematical expression
* @example
*    // Returns -81.4600
*    expr("10.04+9.5-1+-100");
*/ 
function expr (expr) {

    var chars = expr.split("");
    var n = [], op = [], index = 0, oplast = true;

    n[index] = "";
for (var step = 1;step<4;step++){
    // Parse the expression
    for (var c = 0; c < chars.length; c++) {

        if (isNaN(parseInt(chars[c])) && chars[c] !== "." && !oplast) {
            op[index] = chars[c];
            index++;
            n[index] = "";
            oplast = true;
        } else {
            n[index] += chars[c];
            oplast = false;
        }
    }

    // Calculate the expression
    expr = parseFloat(n[0]);
    
    for (var o = 0; o < op.length; o++) {
        var num = parseFloat(n[o + 1]);
        switch (op[o]) {
            case "+":if(step===3)
                expr = expr + num;
                break;
            case "-":if(step===3)
                expr = expr - num;
                break;
            case "*":if(step===2)
                expr = expr * num;
                break;
            case "/":if(step===2)
                expr = expr / num;
                break;
           
            case "^":
                if(step ===1)
                expr = Math.pow(expr,num);
                break;
        }
    }}

    return expr;
}
G=g.splice();
g = g.map(function(b, c, a) {
  ...