Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify nested if/else with repeated results?

I'm trying to simplify the following:

function handleDirection(src) {   if (src === 'left') {     if (inverse) {       tracker--;     } else {       tracker++;     }   } else {     if (inverse) {       tracker++;     } else {       tracker--;     }   } } 

to reduce the number of conditionals. The src will either be 'left' or 'right' always.

like image 223
Rebecca O'Riordan Avatar asked Dec 13 '18 10:12

Rebecca O'Riordan


People also ask

How many nested if statements is too many?

The limit is 7. However, it is possible to circumvent the limitation over the number of nested conditional formulas by cascading them. This article will look at the different methods for nesting multiple IF statements in Excel.

What is the other statement that can avoid multiple nested IF condition in C?

One way i can think is to use variable to store the x, y, z etc and then use the variable inside the if statement to check the condition. for (i = 0; i < N; i++) { a = x; b = y; ... if(a & b !=


2 Answers

You could check with the result of the first check.

This is an exclusive OR check.

// typeof inverse === 'boolean'  function handleDirection(src) {     if (src === 'left' === inverse) {         tracker--;     } else {         tracker++;     } } 

The check evaluates the expression in this order (src === 'left') === inverse:

src === 'left' === inverse ---- first ---             returns a boolean value --------- second --------- take result of former check & compairs it with another boolean 
like image 98
Nina Scholz Avatar answered Oct 10 '22 11:10

Nina Scholz


function handleDirection(src) {    var movement = 1;    if(src === 'left')      movement = -1;     if(inverse)      tracker += movement;    else      tracker -= movement; } 
like image 39
Alays Avatar answered Oct 10 '22 10:10

Alays