44var symbols = {
55 pi : Math . PI ,
66 e : Math . E ,
7+ } ;
8+
9+ var functions = {
710 abs : Math . abs ,
811 min : Math . min ,
912 max : Math . max ,
@@ -24,20 +27,22 @@ var symbols = {
2427 * @returns float or int
2528 */
2629function eval ( expr ) {
27- // Replace symbols
28- for ( var symbol in symbols ) {
29- // Match each symbol only if they are at the beginning or end of the word
30- expr = expr . replace ( new RegExp ( "\\b" + symbol + "\\b" , "g" ) , symbols [ symbol ] ) ;
31- }
32-
3330 // Additionally replace the "," to "."
34- expr = expr . replace ( ',' , '.' )
35-
31+ expr = expr . replace ( "," , "." ) . replace ( " " , "" )
32+
3633 // Only allow numbers, operators, parentheses, and function names
37- if ( ! / ^ [ 0 - 9 + \- * / ^ ( ) . , \s ] * $ / . test ( expr . replace ( / \b [ a - z A - Z ] + \b / g, "" ) ) ) {
34+ if ( ! / ^ [ 0 - 9 + \- * / ^ ( ) e . , \s ] * $ / . test ( expr . replace ( / \b [ a - z A - Z ] + \b / g, "" ) ) ) {
3835 throw "Invalid characters in expression" ;
3936 }
4037
38+ // Replace symbols and functions
39+ for ( var symbol in symbols ) {
40+ expr = expr . replace ( new RegExp ( "\\b" + symbol + "\\b" , "g" ) , symbols [ symbol ] ) ;
41+ }
42+ for ( var func in functions ) { // Warning : not really a map
43+ expr = expr . replace ( new RegExp ( "\\b" + func + "\\b" , "g" ) , "Math." + func ) ;
44+ }
45+
4146 // Eval with function to avoid issues with undeclared variables
4247 return Function ( '"use strict"; return (' + expr + ')' ) ( ) ;
4348}
0 commit comments