About 2K non-minified, non-gzipped. Processes the input string with regular expressions (not a single AST!) to allow calling math functions without object prefixes. Rewrites specified infix operators into function calls to allow for x^y
exponentiation. Outputs a callable js function that runs almost as fast as native code. Highly configurable. Nice, minimal API. Runs in browser and in node.
parser(scope, infix)
creates a parser instance. Properties of thescope
object can be accessed as globals in the input. Anykey
ininfix
object is converted intoinfix[key](arg1, arg2)
. Returns a function. Both arguments are optional and default to empty objects. Examples:
var parseReal = parser(Math, {'^': 'pow'}); // usually you want this
var parseCos = parser({cos: Math.cos}, {});
var plainParse = parser();
var arithmParse = parser({}, {'^': pow});
<parser instance>(expr, args)
convertsexpr
string into a js function with argument order specified withargs
, an optional (no arguments assumed) comma-separated list or an array. Examples:
parseReal('(2 + x)^2 + sin(y)', 'x, y')
// --> function(x, y) { return Math.pow(2 + x, 2) + Math.sin(y); }
parseCos('cos(x) + Math.cos(x)', 'x');
// --> function(x) { return Math.cos(x) + Math.cos(x); }
plainParse('2 + 2');
// --> function() { return 2 + 2; }
- Garbage in -- garbage out. No input validation. When an invalid string is supplied, the paser may crash on compilation. Wrap with try / catch.
- Limited infix operator support. All operators have the same precedence and are left-associative.
- No default configuration. See this API for useful setups.
- (Almost) no sugar. Processing only affects scoping and infix operators.
sin x
for function application andx y
for product are invalid. - String literals may go wrong. Processing also affects them.
- Scoping rules imitate js. Arguments override parser scope, parser scope overrides global scope.
- Scope is stored by reference. If it mutates, the functions use the new values. If properties are added or removed, things can go wrong.
Object.seal
suggested for scope object in ES5 environments.