A calculator (console application) built with Node.js
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.
- 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
- 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
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
npm run test:cover
npm run test
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
- Given the expression;
- Uses Regular Expression just to early avoid typos;
- Convert the original expression into a list of tokens:
- 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