Variable name and operator constraints in math.js

I am using math.js to test math equations for missing closing parentheses or duplicate operators, etc., so the following would be treated as an invalid equation:

9 + ((5 * 6)//12

      

This works great. However, what I am trying to do is resolve the variable name in the equation, for example:

9 + (variableName * 6) / 12

      

The variable name must also match. Thus, the validator will need to know that it is ok if it finds "variableName" in the expression.

Also I want to restrict the allowed equation operators to only the following words:

()-+/*

      

I tried to find answers to these questions in the documentation, but no luck.

Does anyone know how this is done in math.js?

+3


source to share


1 answer


What you can do with math.js, parse the expression in the tree node:

var tree = math.parse('9 + (variableName * 6) / 12');

      

In the current version of math.js, you can parse the tree using a function find

(undocumented, see explanation here ). The next version of math.js will have more extensive (and documented) support in the form of functions traverse

and transform

that will allow you to easily iterate over all the nodes in the tree and do something.

With these functions, you can for example find all SymbolNodes and check if they are allowed and find all OperatorNodes and check if they are allowed. I created a jsbin for you to demonstrate how you can parse the parsed expression:



http://jsbin.com/duduru/1/edit?html,output

Alternatively, you can create your own parser using PEG.js or Jison .

EDIT: The latest version of math.js now officially supports operations on expression trees, see the documentation: http://mathjs.org/docs/expressions/expression_trees.html

+1


source







All Articles