Addition and subtraction within bounds
How would you write the follo开发者_开发知识库wing in JavaScript:
Row-=21;
if (Row < 1) {
Row = 1;
}
You can do this:
Row = Math.max( Row-21, 1);
EDIT:
If you want to be able to set a minimum and/or maximum range, you could prototype your own function into Number.
Number.prototype.adjust = function( adj, min, max ) {
if( isNaN( min ) ) min = -Infinity;
if( isNaN( max ) ) max = Infinity;
var res = this + ~~adj;
return res < min ? min : res > max ? max : res;
};
Then you can use it like this:
Row = Row.adjust( -21, 1, 50 ); /* adjustment, min, max */
- 1st argument is the adjustment
- 2nd argument is the minimum range (pass null for no min)
- 3rd argument is the maximum range (pass null or leave blank for no max)
Row = Row > 22 ? Row - 21 : 1;
row-=21;
if (row < 1) {
row = 1;
}
It seems like already-valid JS.
The only difference would be that you would need to declare your "row" variable as:
var row = 0;
Just for fun, here's a way that replaces the role of the operator with a function:
function makeBoundedOp( bound, addOrSub ){
var newfunc = function newfunc(value,change){
if( addOrSub === 'add' ){
var upperbound = bound;
return (value+change > upperbound) ? upperbound : value+change;
} else {
var lowerbound = bound;
return (value-change < lowerbound) ? lowerbound : value-change;
}
}
return newfunc;
}
Now build up any special-purpose bounded operator functions you need:
var subtractBoundedOne = makeBoundedOp(1,'subtract');
var subtractBoundedTen = makeBoundedOp(10,'subtract');
var addBoundedFifty = makeBoundedOp(50,'add');
Then:
var row = 20;
subtractBoundedOne(row,12); // 8
subtractBoundedTen(row,12); // 10
addBoundedFifty(row,37); // 50
精彩评论