switch case javascript (simplify this code)

Asked

Viewed 159 times

3

I wonder if there’s any way to simplify this code... in the example 1 to 7 I want the same result but so far are few but... and if there were many numbers would have like not to have to put so many cases or it would be better to use if same?

let codigo = 7;
switch(codigo){
    case 1:
    case 2: 
    case 3: 
    case 4:
    case 5:
    case 6:
    case 7: 
        console.log("Acertou");
        break;
    case 8:
        console.log("Poderia ser mas... não é.");
        break;
    default:
        console.log("Tente mais tarde");
        break;

}
  • It has how to simplify this code !!! even has, in this context a if in my opinion is better, now if it is many ... usually the code has something that we do not know, maybe with comparison.

  • I do with pathern test of regex, it gets very small

1 answer

3

In this case I wouldn’t use the switch. You could simplify with the help of a vector or a simple if, depending on the case. See:

Vector-shaped:

let accepted_answers = [1,2,3,4,5,6,7];
let maybe = [8]
let answer= 8;

if(accepted_answers.indexOf(answer) !== -1){
    console.log("Acertou");
}else if(maybe.indexOf(answer) !== -1){
    console.log("Poderia ser mas... não é.");
}else{
    console.log("Tente mais tarde");
}

Only if:

let answer = 7;

if(answer >= 1 && answer <= 7){
   console.log("Acertou");
}else if(answer === 8){
   console.log("Poderia ser mas... não é.");
}else{
   console.log("Tente mais tarde");
}

I would particularly use vectors for having more flexibility and ability to mount the vector of accepted answers more dynamically without having to go back to code.

One more point about the index:

https://www.w3schools.com/jsref/jsref_indexof_array.asp

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

  • 1

    more ai you would have to create a vector with multiple positions? it is unviable !

  • 1

    @Virgilionovic depends on the context. I based the code on the information in the question. I could for example have this vector ready stored in a database and it would be perfectly feasible.

  • if it comes from the database can be made in SQL this comparison, of course if you have control for it, if it comes from an API you can make an index because the array is already ready, but if you do it is impractical.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.