mardi 30 novembre 2021

Operators in an if-else statement [duplicate]

I want to have a logic that returns a value based on 2 variables: a received value and a current value. I have simplified it from multiple else-if's to an operator.

The code is something like this:

var receivedState = 2;
var currentState = 1;
var allowedState = true;

if(receivedState == 2 && currentState !== 1) { 
  allowedState = 1;
} else if ((receivedState == 3 || 4 || 5) && (currentState !== 2)) { 
    allowedState = 2;
}

console.log(allowedState);

So what I am trying to do is if the received state is "2" AND current state is not "1" then I want to set the value of allowedState to 1.

What happens now is that it sets the value to 2.

For the other it does work. When the state is 3, 4 or 5 and the current state is not 2 then the value of allowedState is set to 2 except when the current state is something else than the value of 2, then the value of allowedState is 2.

How do I change my code so that the logic works as following:

If received value is 2 and current value is not 1 then return 1, else do nothing (return true). If received value is one of 3, 4 or 5 and current value is not 2 then return 2, else do nothing.

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire