This is how I checkout to see if a number is in a range (in between two other numbers):
var a = 10,
b = 30,
x = 15,
y = 35;
x < Math.max(a,b) && x > Math.min(a,b) // -> true
y < Math.max(a,b) && y > Math.min(a,b) // -> false
I have to do this math in my code a lot and I'm looking for shorter equivalent code.
This is a shorter version I came up with. But I am sure it can get much shorter:
a < x && x < b
true
a < y && y < b
false
But downside is I have to repeat x
or y
To check if a number is between two numbers: Use the && (and) operator to chain two conditions. In the first condition check that the number is greater than the lower range and in the second, that the number is lower than the higher range. If both conditions are met, the number is in the range.
If x is in range, then it must be greater than or equal to low, i.e., (x-low) >= 0. And must be smaller than or equal to high i.e., (high – x) <= 0. So if result of the multiplication is less than or equal to 0, then x is in range.
The min() function returns the smallest value from the numbers provided. If no parameters are provided, the min() function will return Infinity. If any of the parameters provided are not numbers, the min() function will return NaN.
Number.prototype.between = function (min, max) {
return this > min && this < max;
};
if ((5).between(4, 6)) {
alert('worked!');
}
var num = 6;
if (num.between(5, 7)) {
alert('still worked!');
}
http://jsfiddle.net/jbabey/4jjRm/1/
Note that you need to surround number literals in parens, or the interpreter will think your property is a decimal point and blow up.
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