detect 4 permutations of 2 variable values in a switch case statement

 

Questions


I have 2 variables, width and height as integers. Any of these can be positive or negative (not zero). So naturally there are 4 cases;

  1. width > 0 && height > 0
  2. width > 0 && height < 0
  3. width < 0 && height > 0
  4. width < 0 && height < 0

Now I want to take different action on each of these 4 cases without using 4 if statements.

Is there a way to aggregate these cases so that it can be put as a simple switch case

switch( aggregate ){
  case 1:
  case 2:
  case 3:
  case 4:
}

If there is no better way than using if for each then in 3D space you have 3 lengths (x,y,z) and there will be 27 if blocks.

I’m using javascript if that matters.

 

 

————————————————-

Answer

In javascript this is quite easy, just turn the condition upside down:

switch(true)
{
    case (width > 0 && height > 0):
        break;
    case (width > 0 && height < 0):
        break;
    case (width < 0 && height > 0):
        break;
    case (width < 0 && height < 0):
        break;

    default:

}

This also works in VB6/VBA but not in many other languaguages like C++ and C#.

Here’s a simple proof: http://jsfiddle.net/avuxj/

coding-style,geometry,math

Facebook Comments

Post a comment