Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate an Equation in Javascript, without eval()

I have a bunch of fields in a web page (150+) that need to have equations run on them to produce a result.

I currently store the equation like this:

<input name="F7" type="text" class="numeric" data-formula="([C7]-[D7])/[E7]" readonly />

When an input is blurred, I use a jQuery selector to iterate over all inputs with a data-formula attribute, take the formula, and use regex to replace the pointers (the [C7] in the equation) with their appropriate values.

After that, I eval() the equation to get a result, and put it in the correct input. This works great, but is very slow and results in the web page hanging for a few seconds, which is bad if it happens every time an input is blurred.

Is there a way to evaluate an equation, such as "(1-2)/4", without using eval()? These equations also may have functions, such as square root (which makes eval() nice, since I can just put Math.sqrt() in the formula), and the numbers may be decimals.

Note: This application must run on IE7 and 8, so I don't believe I can use Webworkers or anything like that. I have also considered only running this code after a "Save" button is hit, but I would prefer the UI to update live if possible

like image 322
Andrew M Avatar asked Jul 10 '12 21:07

Andrew M


1 Answers

I only really know two alternatives, one is to use a script element that is dynamically written to the page, e.g.:

function evaluate(formula)
{
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.text = "window.__lr = " + formula + ";";
  document.body.appendChild(script);
  document.body.removeChild(script);

  var r = window.__lr;

  return r;
}

The other would be to use new Function(...):

function evaluate3(formula)
{
  var func = new Function("return " + formula);
  return func();
}

But I don't think you'll find something that yields similar performance to eval: http://jsperf.com/alternative-evaluation

The performance of eval varies across browsers and platforms, have you got a specific browser/platform combination in mind? The newer javascript engines in improved browsers will offer optimised eval:

Test Results

This is only a limited set of tests on a few UAs, but it should give you an idea of how it performs in different environments.

like image 143
Matthew Abbott Avatar answered Sep 30 '22 20:09

Matthew Abbott