A more compact way to do this?
I have a couple of functions that move around the surrounding cells of a cell. The grid is contained within the array.
In my code, I have checks to make sure it is not one of the extreme cells, as checking a cell for undefined throws an error.
Thus, 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;
}
Many lines of code do very little. Is there a more elegant way to do this?
a source to share
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 can remove the redundancy by writing a function to calculate the "first" given the value as well as the "last" - but I think that would be overkill in this case.
a source to share
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:
An alternative way of using it is suggested as John has already posted "my" code.;)
Edit 2:
As Raphael pointed out, the condition can be implicitly converted to a number, so the conditional statement 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 is less obvious what this code actually does. From my tests it seems that Javascript consistently uses the value 1 for true, but in all programming languages the value -1 is also widely used.
a source to share