I'm attempting to decode this bit of code I found in Raphael.js's source (it converts from an HSL color to an RGB color, this is only a part of the function):
var R, G, B, X, C;
h = (h % 360) / 60;
C = 2 * s * (l < .5 ? l : 1 - l);
X = C * (1 - abs(h % 2 - 1));
R = G = B = l - C / 2;
h = ~~h;
R += [C, X, 0, 0, X, C][h];
G += [X, C, C, X, 0, 0][h];
B += [0, 0, X, C, C, X][h];
Now, I know what h = ~~h does (basically floors a number with a few key differences), but I can't figure out for the life of me what this means:
R += [C, X, 0, 0, X, C][h];
Why is he creating an array then referencing [h] on it? Is he finding the value that the variable h is equal to out of a set of values? (but why would he do that if he already knows h's value?) I've never actually seen anything like this and if that's the case I deem it extraordinarily clever.
h will be the index in the array. This is indeed a somewhat convoluted code, maybe using a switch statement or something similar would be clearer in this case. h is a number between 0 and 5 (modulo 360, divided by 60).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With