views:

130

answers:

4

I have a couple of functions that loop around the surrounding cells of a cell. The grid is contained inside an array.

In my code, I have checks to make sure it's not one of the edge cells, as checking an undefined cell causes an error.

As such, I have code like this:

if(x > 0) {
    var firstX = x - 1;
} else {
    var firstX = x;
}
if(x < 199) {
    var lastX = x + 1;
} else {
    var lastX = x;
}

if(y > 0) {
    var firstY = y - 1;
} else {
    var firstY = y;
}
if(y < 199) {
    var lastY = y + 1;
} else {
    var lastY = y;
}

A lot of lines of code to do very little. Is there a more elegant way to do this?

+9  A: 

You can use the conditional operator:

var firstX = x > 0 ? x - 1 : x;
var lastX = x < 199 ? x + 1 : x;
var firstY = y > 0 ? y - 1 : y;
var lastY = y < 199 ? y + 1 : y;

You could remove the redundancy by writing a function to calculate "first" given a value, and a similar one for "last" - but I think that would be overkill in this case.

Jon Skeet
Thanks. I know there was something simple I was overlooking.
Macha
+4  A: 

You can use the conditional operator:

var firstX = x - (x > 0 ? 1:0);
var lastX = x + (x < 199 ? 1:0);
var firstY = y - (y > 0 ? 1:0);
var lastY = y + (y < 199 ? 1:0);

Edit:
Offered an alternative way of using it, as Jon already posted "my" code. ;)

Edit 2:
As Rafael pointed out, the condition can be implicitly converted into a number, so the conditional operator is not needed:

var firstX = x - (x > 0);
var lastX = x + (x < 199);
var firstY = y - (y > 0);
var lastY = y + (y < 199);

However, it's less obvious what this code actually does. From my tests it seems that Javascript consistently uses the value 1 for true, but across programming languages the value -1 is just as commonly used.

Guffa
the ternary operator isn't needed. You can just writevar firstX = x - (x > 0)JS will automatically convert the boolean value to Number
Rafael
@Rafael: I'd say that's less readable than using a conditional though.
Jon Skeet
@Jon Skeet: yes, it is less readable, but it's more compact and we use features of the javascript language. Logical true is being converted to 1 (number value) and false to 0.
Rafael
+9  A: 

Or more clearly:

var firstX = Math.max(x - 1, 0);
var lastX = Math.min(x + 1, 199);
var firstY = Math.max(y - 1, 0);
var lastY = Math.min(y + 1, 199);
fmark
That's assuming that x and y are in the range [0, 199]. That may well be the case, but it's an assumption. (Consider x = -10: the original code would make firstX= -9, yours would give 0.) Other than that, I like it though.
Jon Skeet
Well if x or y < 0 or > 199, something's gone wrong elsewhere in the code, as under normal circumstances, x and y should be between 0 and 199.
Macha
A: 

Use the variables that you check(x and y) instead of First/lastX and First/lastY

if(x > 0 && x < 199) x-=1;
else if(x > 0) x+=1;

if(y > 0 && y < 199) y-=1;
else if(y > 0) y +=1;

Just check x and y after that. :)

John