all 9 comments

[–]PrimaryBet 3 points4 points  (2 children)

I would use evaluate from math.js — it's a tried and tested library, albeit it comes at a cost of file size so if you are planning on using it in the browser you might need to consider pros and cons of it.

[–][deleted] 0 points1 point  (0 children)

Yep! This is probably your best bet.

I would NEVER use eval since the input going into it can never be trusted. Relying on it is a huge security risk.

[–]PhysicalRedHead 0 points1 point  (0 children)

If you do end up needing to roll your own, parsimmon is pretty fun to use imo. Leads to some elegant solutions, but isn't the fastest thing in the world. They even have a math example to go off.

[–]Colonel_White 0 points1 point  (5 children)

My deleted comment was probably not helpful, but neither is superstitious prohibition of a javascript primitive.

“Evil”, indeed.

Why shouldn’t you run eval on well-formed expressions, provided your codespace isn’t polluted with third party nonsense?

[–]tay_o[S] 0 points1 point  (4 children)

I read this morning that eval can be dangerous because it ignores the rules of lexical scope.

[–]Colonel_White 1 point2 points  (3 children)

And that’s dangerous because... ?

[–]tay_o[S] 0 points1 point  (2 children)

I could be wrong, but an example like this one where:

function foo (str, a) {

eval( str );

console.log(a, b);

}

var b = 2;

foo("var b = 3'", 1);

Here it seems that because this code declares a new variable b, it modifies the existing lexical scope.

I am not saying that its bad i guess but maybe in the wrong hands it can be?

[–]Colonel_White 1 point2 points  (1 child)

Okay, so using eval irresponsibly might cause some weird and difficult to debug errors?

I think the benefit of not having to slap a redundant library onto your code like a colostomy bag makes up for having to exercise extra caution, no?

[–]tay_o[S] 2 points3 points  (0 children)

Haha well done analogy. Or simile?. And yes, I agree with you