Alternative for multiple if statements

前端 未结 4 1218
情话喂你
情话喂你 2021-01-14 09:19

My code contains a lot of multiple if statements. Is there any other way to get rid of these statements. For example suppose I have the following conditions

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-14 09:35

    OK, assuming you really have a lot of ifs and your ts are fixed integers, and the main goal is readability of your many, many "rules". Then you can try the following.

    First I would make sure that all ts have a valid value and skip the undefined cases. If the variables t are real logic values rather than numbers I would also use only explicit rules (e.g., t1 == 0 instead of using >, <, >=, <=), esp. if the rules you want to implement are as diverse as those expressed in your if statements.

    Then you could encode the logic using a numeric system, e.g., using decimals for good readability. For each t you use one decimal position of a the new "logic number" that encodes your logic:

    111 means t1 == t2 == t1 == 1
    201 means t1 == 2, t2 == 0, t3 == 1
    etc.
    

    The number is easily created from your t1,t2, and t3:

    num = t1*100 + t2*10 + t3
    

    The switch-case below implements your logic. It is an unfolded version of your if rules. By not allowing for multi value checks (via >=, etc.) we need to specify a rule for every combination you want to handle. This might increase the number or rules you have to specify but might also make your logic rules more readable and maintainable.

    var getFadeInClass = function(t1,t2,t3) {
        // for the sake of shortness I use ".b" instead of ".b_class" etc.
        var num = t1*100 + t2*10 + t3
    
        switch(logic_state){
        case 100:; case 200:; case 300: return ".b"
        case  10:; case  20:; case  30: return ".c"
    
        case   1:                       return ".d"
    
        case 110:; case 120:; case 130:;
        case 210:; case 220:; case 230:;
        case 310:; case 320:; case 330: return ".b.c"
    
        case 101:; case 102:; case 103:;
        case 201:; case 202:; case 203:;
        case 301:; case 302:; case 303: return ".b.d"
    }
    return ""
    

    }

    You could also use Math or other kinds of test to reason on the numbers.

    var x = t1*100 + t2*10 + t3
    if ( x != 0 && x%100    == 0)  return "b"
    if ( x != 0 && x%100%10 == 0)  return "c"
    if ( x == 1 )                  return "d"
    

    But I would prefer the switch-case because it reads more nicely. I hope this is what you wanted to achieve. :)

    You can check out a running version of this decimal logic in this fiddle.

    Cheers, Juve

提交回复
热议问题