1

I know nothing about javascript and need help interpreting the following:

{
    var d = max - min;
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
    switch(max){
      case r: h = (g - b) / d + (g < b ? 6 : 0); break;
      case g: h = (b - r) / d + 2; break;
      case b: h = (r - g) / d + 4; break;
    }
}

Could someone please explain what this means so I can code an equivalent in Objective-C ?

Thank you!

or to make my question even more to the point. could you please translate (to human language) the following line for me ?

s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
EarlGrey
  • 2,514
  • 4
  • 34
  • 63

4 Answers4

4
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);

the expression ? value1 : value2 operator evaluates the expression and, if it's true, returns value1, else returns value2. so in that particular case, it will evaluate l > 0.5, if that's true it'll set s to d / (2 - max - min), else it'll set s to d / (max + min)


EDIT in response to comment:

I don't really know a lot of Javascript at all, but as for the switch statement, it seems to be using variable cases. That's not allowed in Objective-C (or C, for that matter). But it seems to be trying to find which of the r, g or b variables is equal to the max variable...

In Objective-C (or C, or C++) a switch statement can only use constant case values, like this:

switch (myVariable)
{
    case 0:
        //do something if myVariable == 0
        break;
    case 1:
        //do something if myVariable == 1
        break;
    case 2:
        //do something if myVariable == 2
        break;
}

I'm gonna take a guess here and say that in javascript with variable cases, it would probably be equivalent to something like

if (max == r)
    h = (g - b) / d + (g < b ? 6 : 0);
else if (max == g)
    h = (b - r) / d + 2;
else if (max == b)
    h = (r - g) / d + 4;

if anyone who knows more about javascript could confirm that for us, it would be great.

filipe
  • 3,370
  • 1
  • 16
  • 22
1

This is actually very straightforward, all you have to do is change var to float.

Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
0

Seems to be a fragment from an algorithm to assign new RGB colors to something. Can't tell without any info about the values max, min. d is probably "distance".

var s is assigned something with a ternary ?: operator, but s is not used again in the block-

knb
  • 9,138
  • 4
  • 58
  • 85
-1

I'd say it means that whomever you inherited that code from needs to learn how to name variables properly.

Adam Milligan
  • 2,826
  • 19
  • 17
  • 2
    Just passing by, but can't help commenting: looks like this code converts RGB into HSL, which means that variables named h, s and l actually make perfect sense. And the purpose of the 'd' variable is perfectly clear from the first assignment (when you see d = max - min, you know that it stands for 'delta' or 'distance'). So I wouldn't say the names are bad. – Andrey Tarantsov Jul 09 '12 at 17:34