Shortening a Javascript if-else structure

前端 未结 7 827
情书的邮戳
情书的邮戳 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:16

    Of course calling value(d) multiple times is something you can avoid.

    Also you can shorten a little using the symmetry:

      var level = function (d) {
        //
        //               -std    median  +std
        // ----------------|-------|-------|------------------
        // 4444444444444444 3333333 2222222 111111111111111111
        //
        var i = Math.floor((median - value(d)) / stddev) + 3;
        return Math.max(1, Math.min(4, i));
      };
    

    Probably not a good idea for a real project however... I didn't test but I wouldn't be surprised to find this code slower than the original in your question and for sure I find it harder to maintain.

    Note that excluding one-shot throwaway scripts normally code is written once and read many times (for maintenance like improvements or debugging), thus "easier to read" is normally much more important than "easier to write".

    When shorter means "easier to read" is a good thing, when it starts meaning "harder to read" it's not.

提交回复
热议问题