A somewhat painful triple-nested ternary operator

后端 未结 9 1524
北恋
北恋 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:31
    H = C == 0 
        ? null 
        : V == r 
            ? (g - b) / C 
            : V == g 
                ? (b - r) / C + 2 
                : (r - g) / C + 4
    

    I've seen Dan Abramov using this indentation placement pattern. While I don't like how the conditional operator ? no longer visually follows the condition, I prefer this to something like @lolmaus's example in that the indentation will always be consistent regardless the size of the conditional.

    You actually start to look at it as ? true : false which is visually intuitive here. And this way, I find the ternary is much easier to spot and differentiate from the surrounding code.

    0 讨论(0)
  • 2020-12-30 20:31

    Yes, it's right (apart from capitalisation differences). Yet, it may be cleaner written without any parentheses, readable as elseif:

    if (C == 0)
        h = null;
    else if (V == r)
        h = (g - b) / C;
    else if (V == g)
        h = (b - r) / C + 2;
    else
        h = (r - g) / C + 4;
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-30 20:46

    To my personal taste, a carefully aligned nested ternary beats the if-esle mess:

    const H =
      C == 0 ? null            :
      V == r ? (g - b) / C     :
      V == g ? (b - r) / C + 2 :
               (r - g) / C + 4 ;
    
    0 讨论(0)
  • 2020-12-30 20:47

    Here's another, more elegant idea...

    if (C != 0) 
    {
      if (V == r) return (g - b) / C;
      if (V == g) return (b - r) / C + 2;
      return (r - g) / C + 4;
    }
    
    return null;
    

    Just wrap this in function and use instead of H...

    0 讨论(0)
  • 2020-12-30 20:47

    Why not use ternary operators found in Python?

    H = (
        None            if C == 0 else
        (g - b) / C     if V == r else
        (b - r) / C + 2 if V == g else
        (r - g) / C + 4
    )
    
    0 讨论(0)
提交回复
热议问题