Is there a shorthand version of the following:
(a > 0 && a < 1000 && b > 0 && b < 1000 && c > 0 && c < 1000)
Many thanks.
No, there isn't really any shorthand. There is no simple inline way to specify a comparison like that so that it could be repeated for different variables.
You could make a function for validating values:
function between(min, max, values) {
for (var i = 2; i < arguments.length; i++) {
if (arguments[i] < min || arguments[i] > max) return false;
}
return true;
}
and call it using:
between(1, 999, a, b, c)
There are a lot of ways to do this. Personally if I was doing this a lot, I'd define a function once:
function between(val, min, max) { return min < val && val < max; }
Then your if
checks look like:
if(between(a, 0, 1000) && between(b, 0, 1000) && between(c, 0, 1000))
The alternative is to add a method onto the numbers themselves:
Number.prototype.between = function(min,max) { return min<this && this<max; };
Then use it like this:
if(a.between(0, 1000) && b.between(0, 1000) && c.between(0, 1000))
Though this it's much cleaner...or you may want to go another route altogether.
Note: both of these approaches are for you. They will run slower, they're just a bit easier to maintain...the closure compiler would inline most of it with advanced optimizations though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With