You need to write (or use) a parser with operator precedence.
The idea is to turn the equation into a tree, for example.
x + 3 = 3x - 2
Is really a structure
= / \ + - / \ / \ x 3 * 2 / \ 3 x
Where each statement describes an operation between two "branches" of a tree. Using a javascript object, creating a structure is easy.
function tree(lterm,op,rterm) { t.operator = op; t.left = lterm; t.right = rterm; return t; } expression = tree("x", "/", tree("x","+",3) );
Then, by manipulating the tree, you can solve the equation or perform calculations. To evaluate an expression (without any unknowns), you run a tree starting at the terminals and up from intersection to intersection. You can replace a section of a tree with a result or annotate it with a result - add a result variable to the tree object.
Here are some useful methods to include in a tree class:
- getLeft
- Getright
- prettyPrint
- estimate
- rate ("x", 5) // x = 5, now rate ...
These are not just linear operations that can be βparsedβ in this way. The best parsers will have a list of operators, which includes = * / + - but also unary operators: - () sin cos ...
I did not use operator syntax parser in javascript, but some of them must exist in advance. Of course, a good soul on this site will add a good link or two to my answer.
By the way, the tree-based approach has many applications. In a spreadsheet:
A2 = A1+B1
In a boolean solver:
A = not (B or C) C = true
In XML parsing:
<main> <part>A</part> <part>B</part> </main>
boisvert
source share