Shortening a Javascript if-else structure

前端 未结 7 820
情书的邮戳
情书的邮戳 2021-02-13 00:05

The code I have is:

 var level = function (d) {
    if (value(d) > median + stdev) {
        return 1;
    } else if (value(d) > median) {
        return 2         


        
7条回答
  •  太阳男子
    2021-02-13 00:33

    I don't see much room for improvements which could guarantee the same readability of the starting case. If you are really returning integers, and they aren't there just for the sake of this example, I would suggest you to return something more meaningful.

    You could for sure compute value(d) just once

    var level = function (d) {
      var dValue = value(d);
      if (dValue > median + stdev) {
        return 1;
      } else if (dValue > median) {
        return 2;
      } else if (dValue > median - stdev) {
        return 3;
      } else {
       return 4;
      }
    };
    

    Also, you might want to avoid multiple returns, or maybe you don't, for me they're the same, each has advanges/disadvantages:

    var level = function (d) {
      var dValue = value(d),
          code = 4;
      if (dValue > median + stdev) {
        code = 1;
      } else if (dValue > median) {
        code = 2;
      } else if (dValue > median - stdev) {
        code = 3;
      } 
      return code;
    };
    

    If you assign a meaningful name to code you are giving even more information to the guy who is reading your code.

提交回复
热议问题