Raymond Sam Chia
Raymond Sam Chia

Reputation: 27

How to stop javascript prompt if function is not met

i have a function that ask the user to choose an operator. After choosing an operator the function will run to see if there is an operator in the function. If there is then fine, the result will come out just fine. But if there isn't an operator, you shouldn't be able to input numbers and it should immediately return the message "Operator not found". But instead, it cycles through all the function and still let the user to input the number eventhough the operator is not found. Here is the code

function go(oper, _num1, _num2) {
    if (oper == "+") {
        return _num1+_num2;
    } else if(oper == "-") {
        return _num1-_num2;
    } else if(oper == "/"){
        return _num1/_num2;
    } else if(oper == "*"){
        return _num1*_num2;
    } else {
        return "Sorry Operator not recognized";
    }
}

alert( go( prompt("- , + , / , *  Choose one = "), parseInt(prompt("Gimme a number")), parseInt(prompt("Second number")) ) );

I want the code to stop asking for number if the operator is not found. What should I do? Thanks in advance. (Sorry, English is not my first language)

Upvotes: 1

Views: 207

Answers (1)

OPTIMUS PRIME
OPTIMUS PRIME

Reputation: 1335

Don't seem you really need the function arguments in this case, as they always would be the same...
One of the ways:

let calc = {
  "+": (a, b) => a + b, 
  "-": (a, b) => a - b, 
  "*": (a, b) => a * b, 
  "/": (a, b) => a / b, 
}

alert( go() );

function go() {
  let oper = prompt("- , + , / , *  Choose the operator:");

  if( oper in calc ){
    let a = +prompt("Gimme a number:");
    if( isNaN(a) ){ return "Not a number!"; }

    let b = +prompt("Second number:");
    if( isNaN(b) ){ return "Not a number!"; }

    return calc[oper](a, b);
  } else {
    return "Sorry Operator not recognized";
  }
}

Upvotes: 1

Related Questions