Problems with conditional statement in jQuery - json

I'm having a problem handling some numbers from a json request. Based on the results I'm trying to output some various bits of HTML. Specifically the problem is when I come to check whether a number is greater than -1, but less than 6. Code excerpt is as follows…
else if(parseInt(myvariable, 10) < -1) {
//this is where one thing happens
}
else if(parseInt(myvariable, 10) > -1) {
//Something else happens here
}
else if(parseInt(myvariable, 10) > 6) {
//This is where the third thing should happen, but doesn't?
}
It seems that despite the value being 7 or 70 the second 'else if' is as far as it gets.
Is there a way that I can check that the number is more than -1 but less than 6 so that it moves on to the next conditional statement.
I'm guessing that (like my previous question) there's a very simple answer so please excuse my naivety.
Thanks in advance.

Conditions are executed only until one is found to be true.
In other words, you need to re-jig their order or tighten them to make your current order work.
7 is above -1, so the second condition resolves to true. So for 7, the 3rd condition is never needed.
if(parseInt(myvariable, 10) < -1) {
//number is less than -1
}
else if(parseInt(myvariable, 10) > 6) {
//number is above 6
}
else {
//neither, so must be inbetween -1 an 6
}

The if condition is wrong. Let's think of this: myvariable is 7.
In your code will happen:
else if(parseInt(myvariable, 10) < -1) {
//this is where one thing happens
}
else if(parseInt(myvariable, 10) > -1) {
**// HERE THE CONDITION IS TRUE, BECAUSE 7 > -1**
}
else if(parseInt(myvariable, 10) > 6) {
// This is where the third thing should happen, but doesn't?
}
You can change it as
else if(parseInt(myvariable, 10) < -1) {
//this is where one thing happens
}
else if(parseInt(myvariable, 10) > 6) {
// This is where the third thing should happen, but doesn't?
}
else if(parseInt(myvariable, 10) > -1) {
// Moved
}
To make it work...

Another solution is to change the second line:
else if(parseInt(myvariable, 10) > -1)
to:
else if(parseInt(myvariable, 10) <= 6)
There are so many ways of writing this.

yes because any number you will write greater than -1 will never go throw the third block of code , it will go throw the second, as you said "the number is more than -1 but less than 6" you can simply do like this :
else if(parseInt(myvariable, 10) < -1) {
//this is where one thing happens
}
else if(parseInt(myvariable, 10) > -1 && parseInt(myvariable, 10) < 6) {
//Something else happens here
}

I guess you can do this easily do something like this:
considering your variable value is (7):
else if(parseInt(myVariable, 10) < -1) {
//this is where one thing happens
}
else if(parseInt(myVariable, 10) > -1) {
//now 'myVariable' is greater than -1, then let's check if it is greater than 6
if(parseInt(myVariable, 10) > 6) {
//this where what you should do if 'myVariable' greater than -1 AND greater than 6
}
}

Related

Incorrect IF Decision in C# - Zed Graph Out of Range Error - RollingPointPairList

This is really mind-boggling. I am using RollingPointPairList of Zed Graph, and I kept getting an error saying Argument Out of Range. So I decided to use the source code of Zed Graph instead of .dll files. I can now see where the exception is thrown. But I am totally perplexed to see why.
This is where the exception is thrown:
Original code from RollingPointPairList:
public PointPair this[int index]
{
get
{
if (index >= Count || index < 0)
{
throw new ArgumentOutOfRangeException();
}
index += _tailIdx;
if ( index >= _mBuffer.Length )
index -= _mBuffer.Length;
return _mBuffer[index];
}
Surprisingly, index was never greater or equal to count, or less than 0.
I modified the code to see what was really going on like this:
if (index >= Count || index < 0)
{
Console.WriteLine(index + " " + Count);
Console.Beep(5000, 1000);
if (index >= Count || index < 0)
{
throw new ArgumentOutOfRangeException();
}
}
So I did hear the beep, and it did output something, but this time did not reach the throw excpetion, because of the second if check.
Here is what I see on the output:
Any idea what could be causing this issue?
P.S. I have made sure that multiple threads do not try to modify RollingPointPairList

windows phone 8 orientation control with if statement

I want to check current orientation of screen with if statement for example.
if(orientation==landscape)
{
a++;
}
What should i use for this kind of job how can i get my current orientation and check it with if statement.
ok i solved my problem
else if (p.X > 10 && p.X < 100 && a >= 1 && Orientation==PageOrientation.Landscape)
{
a--;
link = "cevsen/" + a.ToString() + ".jpg";
}
you can get your current orientation with Orientation and compare PageOrientation.Landscape

How to make a For Loop of a nested IF Statement?

I am trying to make a for loop for this nested if statement in a Bejeweled clone I am practicing to code. As you can see it's pretty dumb to do it this way, because I want to loop through more matches, so I was wondering if there is a more efficient way than going through and making even more silly If statement nests about 7 times AND for each direction since the grid is 8 by 8.
The if ( i !== 0 ) bit is to prevent null errors. I think with the For statement if it were to be used it can be something like if ( i < loopvar ) instead
Thank you :3
if (i !== 0 && map[i][j].name == map[i-1][j].name) // this nest of if statements are gonna check the one to the left of the jewel we are looping through, and see if they match.
{
map[i][j].jewelsWest++;
if ( i !== 1 && map[i-1][j].name == map[i-2][j].name)
{
map[i][j].jewelsWest++;
}
}
I think recursion might me handy in this case:
map[i][j].jewelsWest = countMe(i, j, -1, 0);
map[i][j].jewelsEast = countMe(i, j, 1, 0);
map[i][j].jewelsNorth = countMe(i, j, 0, -1);
map[i][j].jewelsSouth = countMe(i, j, 0, 1);
private function countMe(x, y, xDiff, yDiff):int
{
if(map[x+xDiff] && map[x+xDiff][y+yDiff] && map[x][y].name == map[x+xDiff][y+yDiff].name)
{
return 1 + countMe(x+xDiff, y+yDiff, xDiff, yDiff);
}
else
{
return 0;
}
}

Switch statements and ranges of numbers

How do you craft a switch statement in as3 to make the case apply to an entire range of numbers?
if (mcPaddle.visible == true)
{
switch (score)
{
case 10://10 to 100
myColor.color = 0x111111;
break;
case 110://110 to 1000
//etc etc
break;
}
}
I've tried multiple ways to make the case apply for all numbers between 10-100, and 110-1000, but can't seem to find a way to do it, and I can't find the proper syntax for such a thing in as3.
You can use a switch block :
var score:Number = 123;
switch(true){
case score > 120 && score < 125 :
trace('score > 120 && score < 125');
break;
case score > 100 && score < 140 :
trace('score > 100 && score < 140');
break;
case score == 123 :
trace('score == 123');
break;
}
//score > 120 && score < 125
switch statements just restatements of if (a = b) or (a = c) or (a = d) ... type constructs. THey're not intended for ranges. You can somewhat simulate it using fallthroughs:
switch (score) {
case 10:
case 11:
case 12:
case 13:
case etc...
blah blah blah
break;
}
but that's a ludicrously dumb way to go. Much easier/terser to use a regular if()
ActionScript's switch statement doesn't work with ranges, but you can easily do it with if/else chains:
if (score >= 10 && score <= 100)
{
//10 - 100
}
else if (score <= 110)
{
//101 - 110
}
else if (score <= 1000)
{
//111 - 1000
}
For those looking for how to use this in HTML/jQuery, I've used #OXMO456's answer to create this simple pen: http://codepen.io/anon/pen/jHFoB
You just have to set the var normally and remove the lines starting with trace.
Ps. I'm adding this as an answer since I don't have enough rep to comment on his. If anyone can, please move/copy this there. Thanks!

How to recognize that short code blocks can be refactored into something cleaner?

i have a bit of code that i wrote a few weeks ago (the code's purpose isn't so much important as its structure):
if (_image.Empty)
{
//Use the true image size if they haven't specified a custom size
if (_glyphSize.Width > 0)
imageSize.Width = _glyphSize.Width //override
else
imageSize.Width = _image.GetWidth;
if (_glyphSize.Height > 0) then
imageSize.Height = _glyphSize.Height
else
imageSize.Height = _image.GetHeight
}
else
{
//No image, but they can still override it with a custom size
if (_glyphSize.Width > 0) then
imageSize.Width = _glyphSize.Width
else
imageSize.Width = 0;
if (_glyphSize.Height > 0)
imageSize.Height = _glyphSize.Height
else
imageSize.Height := 0;
}
i was going over it tonight, and as i was cleaning it up, i realized that the cleaned version is must more concise:
//Figure out the final image width
if (_glyphSize.Width > 0)
imageSize.Width = _glyphSize.Width
else if (not _glyph.Empty)
imageSize.Width = _glyph.GetWidth
else
imageSize.Width = 0;
//Figure out the final image height
if (_glyphSize.Height > 0)
imageSize.Height = _glyphSize.Height
else if (not _glyph.Empty)
imageSize.Height = _glyph.GetHeight
else
imageSize.Height = 0;
Note: i've trimmed down the code to bare logical flow, and obfsucated the source language.
In the end i took the nested if's, and inverted them. Doing that allowed this shortening. My question is: how can i recognize this in the future?
What are the tell-tale signs that i've just written some code that can be refactored into something shorter?
Another example i had from a few weeks ago was something akin to a permission check: the user can perform an action:
if they have the permission they can do it
if they don't have the permission, but the override is in effect
Which i initially coded as:
if ((HasPermission || (!HasPermission and OverrideEnabled))
{
...do stuff
}
The logical conditions on that if clause seemed kind of wordy. i tried to reach back to my boolean algebra course to figure out how to simplify it. In the end i could do it, so i ended up drawing a truth table:
Permission Override Result
0 0 0
0 1 1
1 0 1
1 1 1
Which when i look at it is an OR operation. So my if statement became:
if (HasPermission or OverrideEnabled)
{
...
}
Which is obvious and simple. And so now i'm wondering how i couldn't see that to begin with.
Which brings me back to my SO question: What tell-tale signs could/should i be looking for in order to recognize that some block of code needs some TLC?
Here are some guidelines from Code Complete, off the top of my head. That is a good book to get for this sort of thing.
Nested if-else and repeated statements in blocks
Long for-loops
Repeated lines/statements or frequently used operations can be placed in a function
If for some reasons you are copying and pasting a line of code over and over again
I found discrete maths to have an influence in how I wrote if statements now. Usually, I see I am writing two same IF statements in 2 blocks, then I would do some mental 'factoring'.
Specifically related to boolean evaluation, it's worth noting that most(?) modern languages implement lazy evaluation.
That is, if "a" is true, then if(a) and if(a or b) are logically and functionally equivelant; the interpreter stops evaluating when it sees or after a true variable. This isn't very important when a and b are variables, but if they're callables [e.g. if(a() or b())], b() will not get evaluated when a is true.
You can save a lot of keystrokes (and processor time) by learning this well:
if(!userExists()):
if(!createUser()):
errorHandling()
else:
doStuff()
else: doStuff()
becomes
if(userExists() or createUser()): doStuff()
else: errorHandling()
Well done. Now, when I see this:
//Figure out the final image width
if (_glyphSize.Width > 0)
...
//Figure out the final image height
if (_glyphSize.Height > 0)
...
I think there is still more refactoring to do. Extracting code into methods isn't just a great way to eliminate redundant code. It's also a great way to make the code self documenting:
I'd be inclined to reduce the code to:
set_final_image_size
With set_final_image_size and its minions defined like so:
def set_final_image_size:
imageSize.Width = final_image_width;
imageSize.Height = final_image_height;
def final_image_width:
if (_glyphSize.Width > 0)
return _glyphSize.Width;
else if (not _glyph.Empty)
return _glyph.GetWidth;
else
return 0;
def final_image_height:
if (_glyphSize.Height > 0)
return _glyphSize.Height;
else if (not _glyph.Empty)
return _glyph.GetHeight;
else
return 0;
Now that you've separated the width and height logic, and noticed that it's identical - what if you were to add, say, getDimension(Direction direction) and setDimension(Direction direction, int length) to your classes? Now you've got
if (_glyphSize.getDimension(direction) > 0)
imageSize.setDimension(direction, _glyphSize.getDimension(direction))
else if (not _glyph.Empty)
imageSize.setDimension(direction, _glyph.getDimension(direction))
else
imageSize.setDimension(direction, 0);
Extracting the local brings us:
length = _glyphSize.getDimension(direction);
if (length > 0)
imageSize.setDimension(direction, length)
else if (not _glyph.Empty)
imageSize.setDimension(direction, _glyph.getDimension(direction))
else
imageSize.setDimension(direction, 0);
taking it a little further:
length = _glyphSize.getDimension(direction);
if (length == 0 && !_glyph.Empty)
length = _glyph.getDimension(direction);
imageSize.setDimension(direction, length);
Which, to my eyes at least, is starting to look pretty nice.