4

I have created a Chrome extension that can draw the graph of the math equation user has inputted. To get the value of y easily, I used eval() (Yes I know it is bad) because the easiest way to achieve it.

var equ = $("#equ1").val();                //some element

//let's say equ = "2(2^x) + 3x"

//some magic code
//equ becomes "2*(pow(2,x))+3*x"

for(var x = -10; x < 10; x++){
    var y = eval(equ.replace(/x/ig, x));   //calculate y value
    drawPoint(x, y);
}
console.log("Graphing done.");

However, because of the new manifest version 2, I can't use eval anymore. I can't think of any way to manipulate the string. Any idea?

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • 4
    A crazy idea would be to [parse it](http://stackoverflow.com/questions/2932016/parsing-of-mathematical-expressions)... – Passerby Mar 28 '13 at 08:29
  • 1
    So eval is gone, but what about generating a function? It's the same thing, I guess? – MaxArt Mar 28 '13 at 08:34
  • Working on the crazy idea from @Passerby, I've slapped together a shoddy hack: http://jsfiddle.net/FfC3t/. Does it help you? – Rikonator Mar 28 '13 at 14:47
  • @Passerby - Looks like it will be a headache if I try to add in other mathematical functions. – Derek 朕會功夫 Mar 28 '13 at 15:23
  • @Derek朕會功夫 Since your process seems to run independently, another way would be to make it a standalone webpage instead of one browser's extension/webapp so you can use APIs freely. – Passerby Mar 29 '13 at 09:25

2 Answers2

4

The clean way: You could try parsing the expression using Jison and building an AST from the input string. Then, associate functions with the AST node that apply the operations that the nodes represent to data given to them. This would mean that you have to explicitly put every math expression that you want to support in your grammar and your node code, but on the other hand, this would also make it easier to support mathematical operators that JS doesn't support. If you're willing to invest some time, this probably is the way to go.

The dirty way: If your extension is used on normal websites, you might be able to do some kind of indirect eval by injecting a <script> element into the website or so – however, that would likely be insecure.

thejh
  • 44,854
  • 16
  • 96
  • 107
0

Did you try New Function() ... ??

var some_logic = "2*(Math.pow(2,x))+3*x";
args = ['x', 'return (' + some_logic + ');'];
myFunc = Function.apply(null, args);

for (var x = -10; x < 10; x++) {
    var y = myFunc(x);
    console.log(x, y);
}

console.log("Graphing done.");

Fiddle - http://jsfiddle.net/atif089/sVPAH/

Atif
  • 10,623
  • 20
  • 63
  • 96
  • 3
    They're essentially the same thing, I don't think Google Chrome manifest would leave out `eval` but keep `new Function`. And they did not: http://developer.chrome.com/extensions/tut_migration_to_manifest_v2.html – Umur Kontacı Mar 28 '13 at 08:42