Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest code to check if a number is in a range in JavaScript

Tags:

javascript

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

like image 340
Mohsen Avatar asked Oct 09 '12 18:10

Mohsen


People also ask

How do you check if a number is within a range JavaScript?

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.

How do you check if a number is within a 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.

How do you find the smallest number in JavaScript?

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.


1 Answers

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.

like image 113
jbabey Avatar answered Nov 14 '22 21:11

jbabey