A somewhat painful triple-nested ternary operator

后端 未结 9 1570
北恋
北恋 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.

提交回复
热议问题