Draw graph without using eval()

eval, graph, javascript, jquery

Solution

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.

Problem

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?

Original source

Related problems