Shortening a Javascript if-else structure

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

    I'd recommend to avoid multiple calls to value:

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

    Also I've nested the if-else-statements in a (hopefully) more meaningful structure - that depends on your usecase though. Might be more helpful if you returned values like -2, -1, 1 and 2 instead or something. A ternary operator could save you some writing, but it's not necessarily getting clearer.

    Alternatively, some maths could help you:

    function level(d) {
        var diff = value(d) - median;
        return 2 + (diff > 0 ? -.5 : .5) * (Math.abs(diff) > stdev ? 3 : 1);
    }
    

    Though it leads to 3 instead of 4 in case value(d) === median-stdev. See @6502's answer on how to avoid that.

提交回复
热议问题