Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A somewhat painful triple-nested ternary operator

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 of converting it to Python when I bumped into this nice triple-nested ternary operator:

H = (C == 0 ? null :     V == r ? (g - b) / C :     V == g ? (b - r) / C + 2 :              (r - g) / C + 4     ); 

It threw me for a loop because Python doesn't have the same kind of ternary operator that Javascript does. I spent a while looking over it and eventually hashed this somewhat saner code (using only if/else) out of it:

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;         }     } } 

Was my interpretation correct? I'm only asking this because if it isn't correct, I'm faced with a lot of debugging. So. Did I "get it"?

like image 395
Elliot Bonneville Avatar asked May 10 '12 02:05

Elliot Bonneville


People also ask

How do you write a 3 condition ternary operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

What is nested ternary operator?

Nested Ternary Operator in C++It is called a ternary operator because it uses three operands for its operation. It is also called a conditional operator. Ternary operator functions the same as an if-else statement.

Are nested ternary operators bad?

Except in very simple cases, you should discourage the use of nested ternary operators. It makes the code harder to read because, indirectly, your eyes scan the code vertically. When you use a nested ternary operator, you have to look more carefully than when you have a conventional operator.

Can we have nested ternary operator in JavaScript?

You can nest one ternary operator as an expression inside another ternary operator to work as a Nested ternary operator in JavaScript.


1 Answers

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

const H =   C == 0 ? null            :   V == r ? (g - b) / C     :   V == g ? (b - r) / C + 2 :            (r - g) / C + 4 ; 
like image 129
Andrey Mikhaylov - lolmaus Avatar answered Oct 04 '22 08:10

Andrey Mikhaylov - lolmaus