A somewhat painful triple-nested ternary operator

后端 未结 9 1564
北恋
北恋 2020-12-30 20:12

I went looking through Raphael.js\'s source code to find out how he converted RGB values to HSB. I found out the function he did it in and I was in the process

9条回答
  •  天涯浪人
    2020-12-30 20:35

    If your JavaScript codebase contains nested ternary statements like the one in question, consider converting the formatting to daisy chained ternary statements instead.

    H = (C == 0)           // Is C zero?
        ? null             // Then return `null`, else ...
        : (V == r)         // Is V equal to r?
        ? (g - b) / C      // Then return this value, else ...
        : (V == g)         // Is V equal to g?
        ? (b - r) / C + 2  // Then return this value
        : (r - g) / C + 4; // Otherwise fall back to this default value
    

    They simply read top to bottom in a straight line, returning a value as soon as they hit a truthy condition or the fallback.

    Nested Ternaries are Great, Eric Elliot

提交回复
热议问题