paiv

MathCalc - Expression calculator in JavaScript

A parser for basic mathematical expressions, in JavaScript.

Motivation: to have a simple DSL of mathematical expressions, sandboxed from page context. And an exercise in parsing.

Download: source code

Try it here:

Supported operators, ordered by precedence:

  • ( )
  • func(x) (call)
  • - (unary)
  • ^ (power, right associative)
  • * / %
  • + -
  • =
  • , (tuple constructor)

Numbers: 42.3, 1e-7

Built-in functions include everything from Math (exp, cos, etc.). Also aliased in lower case: pi, e, inf.

Using MathCalc object

var calc = new MathCalc();
var expr = calc.parse("2 + 2");
expr.eval();

Handling parse errors:

var expr = calc.parse("-8)");
if (expr.error) {
  alert('Parsing error at ' + expr.error.pos + ': ' + expr.error.text);
}

Using variables

var expr = calc.parse("x^2");
expr.eval(3);

Or pass named parameters:

var expr = calc.parse("x^y");
expr.eval({x:3, y:2});

expr.args provides a list of unbound variables, with their positional index:

{"x":0, "y":1}

Variables can be preserved between calls in a scope object:

var expr = calc.parse("x*2");
expr.scope = {x:3};
expr.eval();

Defining functions

Custom functions can be defined in the scope object. Note that this will override any built-in function/variable with the same name (case sensitive).

var expr = calc.parse("foo(4)");
expr.scope.foo = function(x) { return x * 2; };
expr.eval();

Handling runtime errors

eval could produce runtime errors in expr.scope.runtimeError:

var expr = calc.parse("boo(42)");
expr.eval();  // call to undefined function
if (expr.scope.runtimeError) {
  alert('Error: ' + expr.error.text);
}

Implementation details

Download: source code

Expression parser is a shift-reduce parser. The code has no external dependencies.

Similar projects