PDA

View Full Version : writing better if statements



g5604
March 3rd, 2010, 11:17 AM
Hi,

I have the rather ugly, massive if statement. Is there any way I can compress it somehow?

if ((allSides.rotationY==-180) || (allSides.rotationY==0) || (allSides.rotationY==180) || (allSides.rotationX==-180) || (allSides.rotationX==0) || (allSides.rotationX==180)) {
TweenMax.to(allSides, speed, {rotationY:endPosY,rotationX:endPosX,onUpdate:show HideSides});

sorry, not sure why I can uses the code tags.


thanks!
g.

wvxvw
March 3rd, 2010, 11:37 AM
if (!(allSides.rotationY % 180) ||
!(allSides.rotationX % 180))
{
// Your statement here
}
I had to make an assumption that you wanted any number that is divisible by 180 without reminder to make the condition evaluate to true.
Few things to note:
== (equals) operator has higher priority then || (logical OR) operator. This means that parenthesis inside your conditional are redundant.
Unary operators should not be delimited from the operand by a white space, while binary operators should.
Examples of unary operators: -X, X++, ~X.
Examples of binary operators: X - Y, X * Y, X && Y.

TheCanadian
March 3rd, 2010, 01:02 PM
You could also do:

if(Math.cos(allSlides.rotationY * Math.PI / 180) || Math.cos(allSlides.rotationX * Math.PI / 180)
But that's probably slower than what wvxvw posted.

lordofduct
March 3rd, 2010, 01:14 PM
You could also do:

if(Math.cos(allSlides.rotationY * Math.PI / 180) || Math.cos(allSlides.rotationX * Math.PI / 180)
But that's probably slower than what wvxvw posted.

cos(theta) evaluates true always except for over the interval [ pi/2 +/- pi*N ]

http://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Cos.svg/800px-Cos.svg.png

You may have meant to use !sin

if(!Math.sin(allSlides.rotationY * Math.PI / 180) || !Math.sin(allSlides.rotationX * Math.PI / 180) )


Either way this method is far slower than modulo. Nevermind also the issue of float error that would occur in so many places.

g5604
March 4th, 2010, 04:15 AM
thank you!