Home > Net >  I have attempted to write this node.js calculator code for a while
I have attempted to write this node.js calculator code for a while

Time:12-15

I am trying to write a basic text functioning calculator on node.js that will ask questions and use the answer to produce the solutions. For example it should ask for the first number, the operation then the second number and finally display that your result is .. can somebody help me develop a base for this code? Im a bit lost.

CodePudding user response:

Think you need interaction with console

Here is example and it will help you.

const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question("What is your name ? ", function(name) {
        rl.question("Where do you live ? ", function(country) {
        console.log(`${name}, is a citizen of ${country}`);
      rl.close();
   });
});

rl.on("close", function() {
    console.log("\nBYE BYE !!!");
    process.exit(0);
});

As next steps you need to write normal mathematical functions and call them then.

Update with Sum function

// This is required and it's part of node.js api
const readline = require("readline");
const rl = readline.createInterface({
   input: process.stdin,
   output: process.stdout
 });
// Here we interact with user and ask left side digit
rl.question("Please provide left side digt ", function(leftSide) {
// After user presented digit we're asing for right side
rl.question("Now right side ", function(rightSide) {
// So we have two digits it's time to sum:
/* we're converting  first and second inputs
   and plusing them
*/
   // as output we're getting seft   right in same way we can times,  devide etc
    console.log(`Sum result is ${Number(leftSide)   Number(rightSide)}`);
    rl.close();
  });
});

// As you see we can call different functions during operation.
rl.on("close", function() {
console.log("\nBYE BYE !!!");
process.exit(0);
});

CodePudding user response:

It sounds like you're trying to do create an interactive calculator.

So you're going to want to have pseudocode like this:

while equals_not_requested {
  ask for numbers
  ask for operations
}

You'll need to use a while loop because it will cycle until the equals operator is requested. Meanwhile, your loop cycles and keeps requesting numbers and operators.

I think the best way to do this is to place your numbers and operators into an array, and then you can pipe the whole array into a 'do math' function.

  • Related