Skip to content
Advertisement

Simple CLI calculator in js (least amount of code, using built-in functions only)

I’m trying to build the following calculator in every language and js raises questions.

This is my calculator in python3 that just works in 2 lines using the built-in eval() function:

#!/usr/bin/env python3
while True:
    print(eval(input("Calculate: "))

enter image description here

My goal is to reproduce this calculator with the least amount of code and only using the built-in functions of the given language.

I’m a rookie in js and this is how far I’ve got:

#!/usr/bin/env node
while(true){
    console.log(eval(prompt("Calculate: ")));
}

This is only working in theory and I understand that if I use Node as an interpreter I need to import prompt() and eval() functions to work but I’d like to avoid that because they aren’t built-in and I thought I’d ask here first about the best approach.

Advertisement

Answer

Eval is already a native part of nodejs. Prompt, however, is not so simple, unfortunately. There is no trivial way to do this. I’d recommend to use a minimal library like prompt-sync instead.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement