Search code examples
javascriptif-statementlistjs

How to optimize a large number of if-else if-else expressions


here is the some sample line of codes..

if(loc > 0 || cat > 0 || price > 0 || jsBed <= bedroom || jsBuilt >= built) {    
 /// Condition to checn all true
    return true;
} else if(loc < 0 || cat > 0 || price > 0 || jsBed <= bedroom || jsBuilt >= built) { 
   /////// 1 false other are true 

} else if(loc > 0 || cat < 0 || price > 0 || jsBed <= bedroom || jsBuilt >= built) { 

}

How to handle these condition. if i have 5 statement. Then it must be almost 12+ condition one by one.. if i am checking all the 5 combinations its going to more lines of code do we have any better option to check all the conditions.


Solution

  • If you treat a boolean expression as an integer in javascript, it will evaluate to 0 (for false) or 1 (for true). So you could sum the conditions and then use a switch-case construct to check how many were true:

    var numTrue = 
       (loc > 0) + (cat > 0) + (price > 0) + (jsBed <= bedroom) + (jsBuilt >= built);
    
    switch(numTrue) {
        case 0:
            // do something if no condition is met
            break;
        case 1:
            // do something else if one condition is met
            break;
        // etc...
    }