javascriptnode.jsreadline-sync

How do I include a loop to allow the user to continue using JavaScript calculator until they choose to exit?


I have created a JavaScript simple calculator using the 'readline-sync' library for Node.js to handle terminal input/output. The calculator asks the user which operation they would like to perform (+, -, *, /). After they have selected an operation, it asks for two numbers. It performs the calculation and displays the result e.g. 45+9 = 54. After it displays the result, it should ask if the user wants to perform another calculation. How do I add a loop to allow the user to continue using the calculator until they choose to exit?

Here's my code so far:

const calculator = require('readline-sync');

let operations = ['+', '-', '*', '/'];
let index = null;
let operator = null;
let firstNumber = 0;
let secondNumber = 0;

// Gets the operation question and the options
function operationQuestion(){
    operator = calculator.question("What operation would you like to perform?" 
        +'\nOptions:'
        +'\nAddition ('+ operations[0]+')'
         +'\nSubtraction ('+ operations[1]+')'
          +'\nMultiplication ('+ operations[2]+')'
           +'\nDivision ('+ operations[3]+')\n'
    );

    if (!operations.includes(operator)) {
        console.log("That is not a valid operation");
        operationQuestion();
    }

    // Gets the first and second number
    firstNumber = calculator.questionInt("Type the first number: ");
    secondNumber = calculator.questionInt("Type the second number: ");

    // 4 of the operations
    switch(operator) {
        case '+':
            console.log("The result of "+firstNumber + operator +secondNumber+" = "+ (firstNumber + secondNumber));
            break;
            case '-':
                console.log("The result of "+firstNumber + operator +secondNumber+" = "+ (firstNumber - secondNumber));
                break; 
                case '*':
                    console.log("The result of "+firstNumber + operator +secondNumber+" = "+ (firstNumber * secondNumber));
                    break;   
                    case '/':
                        console.log("The result of "+firstNumber + operator +secondNumber+" = "+ (firstNumber / secondNumber));
                        break;
                        default:
                            console.log("Something went wrong :(");
    }
}

// Logic
operationQuestion();

input = calculator.question("Do you want to perform another calculation?")

Solution

  • I have refactored the code to make it better. It is tested and works fine:

    const calculator = require('readline-sync');
    
    // Gets the operation question and the options
    function operationQuestion(){
    const operations = ['+', '-', '*', '/'];
    
    while (true){
        const operator = calculator.question("What operation would you like to perform?" 
            +'\nOptions:'
            +'\nAddition ('+ operations[0]+')'
             +'\nSubtraction ('+ operations[1]+')'
              +'\nMultiplication ('+ operations[2]+')'
               +'\nDivision ('+ operations[3]+')\n'
        );
    
        if (!operations.includes(operator)) {
            console.log("That is not a valid operation");
            operationQuestion();
        }
    
        // Gets the first and second number
        const {firstNumber, secondNumber} = promptForInput(calculator);
         
        const result = calculate({firstNumber,secondNumber,operator})        
    
        logResults({firstNumber, secondNumber, operator, result});
        
        if(!checkIfToRecalculate(calculator)){
            break
        }
    }
    }
    
    const promptForInput = (calculator)=>{
        firstNumber = calculator.questionInt("Type the first number: ");
        secondNumber = calculator.questionInt("Type the second number: ");
        return {firstNumber, secondNumber}
    }
    
    const calculate = ({firstNumber, secondNumber,operator})=>{
        if (operator === '+') return firstNumber + secondNumber;
        if (operator === '-') return firstNumber - secondNumber;
        if (operator === '*') return firstNumber * secondNumber;
        if (operator === '/') return firstNumber / secondNumber;
    }
    
    const logResults = ({firstNumber, secondNumber,operator, result})=>{
        console.log(`The result of ${firstNumber} ${operator} ${secondNumber} = ${result}`);
    }
    
    const checkIfToRecalculate = (calculator)=>{
        const validInputs = ['y', 'yes', 'no', 'n', 'exit']
        let operator = calculator.question("Do you want to perform another calculation?")
        while(!validInputs.includes(operator)){
            console.log(`${operator} is invalid, enter any of ${validInputs.join(',')}`)
            operator = calculator.question("Do you want to perform another calculation?")
        }
        if (operator.toLowerCase() === 'y' || operator.toLowerCase() === 'yes'){
            return true
        }
        return false
    } 
    
    operationQuestion();