Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Shorthand

Tags:

javascript

Is there a shorthand version of the following:

(a > 0 && a < 1000 && b > 0 && b < 1000 && c > 0 && c < 1000)

Many thanks.

like image 540
freshest Avatar asked Nov 27 '10 12:11

freshest


2 Answers

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)
like image 162
Guffa Avatar answered Oct 08 '22 19:10

Guffa


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.

like image 40
Nick Craver Avatar answered Oct 08 '22 20:10

Nick Craver