Skip to content

A calculator (console application) built with Node.js using AST (Abstract Syntax Tree)

License

Notifications You must be signed in to change notification settings

leogomesdev/ast-calculator-nodejs

Repository files navigation

Calculator

A calculator (console application) built with Node.js

Description

This application allows the user to input verbal math expressions and gets the results using Syntax Tree.

Available operators:

  • plus
  • minus
  • times
  • divided

Samples:

Input Result
1 plus 3 minus 4 0
1 plus (3 times 4) 13
1 plus 1 2
1000 minus 1 999
2 plus 1 minus 5 divided 2 minus 1 -0.5
4 times 4 16
20 divided 5 4
0.5 times 10 5

Please, check the Implementation section for more details.

Main technologies used

  • Node.js: JavaScript runtime built on Chrome's V8 engine
  • TypeScript: Typed JavaScript at Any Scale
  • Jest for unit tests
  • ESLint and Prettier to enforce code styling
  • Husky to force syntax checking before commits

Requirements

For local usage:

For local usage with Docker:

Running

With Docker

  • Be sure you have Docker installed.
  • Build image and run the container:
docker build -t calculator .
docker run -it calculator:latest /bin/sh
  • Start the application:
node dist/app.js

Without Docker

Be sure to install the requirements. If using nvm, you can easily run:

nvm use
  • Install dependencies and start the application:
    npm install
    
    # development
    npm run start:dev
    
    # production
    npm run build
    npm run start

Running unit tests

   npm run test:cover
   npm run test

Implementation

This application uses stdin and stdout as an entry point for the system (just because this way is more simple than implementing a REST API).

How does it work?

Let's considerate this expression:

2 plus 5 times 3
  1. Given the expression;
  2. Uses Regular Expression just to early avoid typos;
  3. Convert the original expression into a list of tokens: Sample of lis of tokens
  4. Parse the tokens, respecting the order of the operators (saliency), to calculate the final result.
  • It's required to follow the math concept of BODMAS. Here is an article about BODMAS. In resume:
    • Do things in Parentheses First
    • Multiply or Divide before you Add or Subtract
    • Otherwise just go left to right