简体   繁体   中英

How to optimize if-statements from method returning boolean

I'm somewhat new to javascript and I just wondered if this is even possible.

Consider this:

if(foo('1')){
    // do something
}
else if(foo('2')){
    // do something else
}
else if(foo('3')){
    // do something different
}
else if(foo('4')){
    // do something completely different
}
...
else if(foo(n)){
    ...
}

foo(stringValue) is a method returning either true or false but the catch is that I can't alter that method in any way (eg changing the return value). Now if I wanted to refactor the code I could probably put all the foo parameter values in a collection, create a method for each of the unique operations from the if-statements, iterate over all parameter values and call the appropriate method whenever foo(n) returned true, but that just seems like a very ugly way of doing it. Is there maybe a better way of achieving this using a switch-statement?

There's this trick you can use if you want to use a switch statement (not sure if it's actually better):

switch( true ) {
    case foo('1'):
        // do something
        break;
    case foo('2'):
        // and so on
        break;
    default:
        // all returned false
}

I would prefer this. Just separating the checking code from the processing code.

var array = ["1", "2", "3", "4"];
var iLength = array.length;
for(var i= 0; i < iLength ;i++)
{
    var strValue = array[i];
    if(foo(strValue))
    {
        break;
    }
}

switch(strValue)
{
    case array[0]:
    //perform operations here for case "1"
    break;
    case array[1]:
    //perform operations here for case "2"
    break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM