Node JS formula parser recursive decent

Available for download at:  BitBucket

Javascript based formula elevator that does not require use of eval.   I wrote this code to test some ideas about how to use function pointers to completely decouple the implementation from class specification.

I used the function pointer style of the command pattern rather than inheritance because I originally intended to use this problem as an experiment in GO and RUST where function pointers are first class citizens.

Once I started playing with ideas in JavaScript the rest just kind of fell out. I don’t like the recursive descent mechanism in JavaScript due to the stack overhead but it would be great for languages that do a better job of tail recursion optimization like Scala.

It works but I would modify to remove recursion before heavier use. Other TODO are in the Readme file at bitbucket.

  • Applies JavaScript GREP to simplify parsing
  • Uses recursive descent parser to apply operator precedence
  • function pointer operator interface makes adding new operators easy.
  • V 0.001
  • (C) Jan-2017, MIT Free Use, No promises, No Warranty

We provide consulting services. Contact

Sample Formula

3+2 =

5 + 4 C + 8 =

-4*6/2 =

3! / 11 A + 9 =

3! / 11 =

0.4 1/x * 3 =

807 * 807 =

9999999999999.0 * 999999999999.0 =

calc.js – main implementation code

[pcsh lang=”js” user=”joexdobs” repos=”node-calc” path_id=”calc.js” revision=”default” tab_size=”2″ hl_lines=”” provider=”bitbucket”/]

 

Test driver code

[pcsh lang=”js” user=”joexdobs” repos=”node-calc” path_id=”calcTest.js” revision=”default” tab_size=”2″ hl_lines=”” provider=”bitbucket”/]

REPL Code

The novel aspect of this REPL is reading characters 1 at a time from stdin in node.js so it can immediately execute the calculation as soon as it encounters the = or \n input from the keyboard.   Most code reading from stdin uses the readln module.  This alternative is more flexible.

[pcsh lang=”js” user=”joexdobs” repos=”node-calc” path_id=”calcREPL.js” revision=”default” tab_size=”2″ hl_lines=”” provider=”bitbucket”/]

Code snippets added dynamically using PCSH syntax highlighter which reads the code directly from BitBucket.

Leave a Reply