Monday, May 20, 2024
49
rated 0 times [  55] [ 6]  / answers: 1 / hits: 115148  / 12 Years ago, thu, may 10, 2012, 12:00:00

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?


More From » if-statement

 Answers
11

I think you can have this to avoid the deep nesting:



var H

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

[#85678] Wednesday, May 9, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cullenmaxl

Total Points: 414
Total Questions: 112
Total Answers: 87

Location: United States Minor Outlying Island
Member since Sat, May 28, 2022
2 Years ago
;