I want to check if a value is in an accepted range. If yes, to do something; otherwise, something else.
The range is 0.001-0.009. I know how to use multiple if to check this, but I want to know if there is any way to check it in a single if statement.
You're asking a question about numeric comparisons, so regular expressions really have nothing to do with the issue. You don't need "multiple if" statements to do it, either:
if (x >= 0.001 && x <= 0.009) {
// something
}
You could write yourself a "between()" function:
function between(x, min, max) {
return x >= min && x <= max;
}
// ...
if (between(x, 0.001, 0.009)) {
// something
}
Here is an option with only a single comparison.
// return true if in range, otherwise false
function inRange(x, min, max) {
return ((x-min)*(x-max) <= 0);
}
console.log(inRange(5, 1, 10)); // true
console.log(inRange(-5, 1, 10)); // false
console.log(inRange(20, 1, 10)); // false
If you must use a regexp (and really, you shouldn't!) this will work:
/^0\.00([1-8]\d*|90*)$/
should work, i.e.
^ nothing before,
followed by 0.00 (nb: backslash escape for the . character)
followed by 1 through 8, and any number of additional digits
or 9, followed by any number of zeroes
$: followed by nothing else
If you're already using lodash, you could use the inRange() function:
https://lodash.com/docs/4.17.15#inRange
_.inRange(3, 2, 4);
// => true
_.inRange(4, 8);
// => true
_.inRange(4, 2);
// => false
_.inRange(2, 2);
// => false
_.inRange(1.2, 2);
// => true
_.inRange(5.2, 4);
// => false
_.inRange(-3, -2, -6);
// => true
I like Pointy's between function so I wrote a similar one that worked well for my scenario.
/**
* Checks if an integer is within ±x another integer.
* #param {int} op - The integer in question
* #param {int} target - The integer to compare to
* #param {int} range - the range ±
*/
function nearInt(op, target, range) {
return op < target + range && op > target - range;
}
so if you wanted to see if x was within ±10 of y:
var x = 100;
var y = 115;
nearInt(x,y,10) = false
I'm using it for detecting a long-press on mobile:
//make sure they haven't moved too much during long press.
if (!nearInt(Last.x,Start.x,5) || !nearInt(Last.y, Start.y,5)) clearTimeout(t);
If you want your code to pick a specific range of digits, be sure to use the && operator instead of the ||.
if (x >= 4 && x <= 9) {
// do something
} else {
// do something else
}
// be sure not to do this
if (x >= 4 || x <= 9) {
// do something
} else {
// do something else
}
You must want to determine the lower and upper bound before writing the condition
function between(value,first,last) {
let lower = Math.min(first,last) , upper = Math.max(first,last);
return value >= lower && value <= upper ;
}
const inRange = (num, num1, num2) => Math.min(num1, num2) <= num && Math.max(num1, num2) >= num;
Could be like this if you want to make inRange inclusive and not depend on order of range numbers (num1, num2).
Related
How do I figure out if a variable is divisible by 2? Furthermore I need do a function if it is and do a different function if it is not.
Use modulus:
// Will evaluate to true if the variable is divisible by 2
variable % 2 === 0
Seriously, there's no jQuery plugin for odd/even checks?
Well, not anymore - releasing "Oven" a jQuery plugin under the MIT license to test if a given number is Odd/Even.
Source code is also available at http://jsfiddle.net/7HQNG/
Test-suites are available at http://jsfiddle.net/zeuRV/
(function() {
/*
* isEven(n)
* #args number n
* #return boolean returns whether the given number is even
*/
jQuery.isEven = function(number) {
return number % 2 == 0;
};
/* isOdd(n)
* #args number n
* #return boolean returns whether the given number is odd
*/
jQuery.isOdd = function(number) {
return !jQuery.isEven(number);
};
})();
You don't need jQuery. Just use JavaScript's Modulo operator.
You can use the modulus operator like this, no need for jQuery. Just replace the alerts with your code.
var x = 2;
if (x % 2 == 0)
{
alert('even');
}
else
{
alert('odd')
}
You can do it in a better way (up to 50 % faster than modulo operator):
odd: x & 1
even: !(x & 1)
Reference: High Performance JavaScript, 8. ->Bitwise Operators
You can also:
if (x & 1)
itsOdd();
else
itsEven();
if (x & 1)
itIsOddNumber();
else
itIsEvenNumber();
Hope this helps.
let number = 7;
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
Here is a complete function that will log to the console the parity of your input.
const checkNumber = (x) => {
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
}
var x = 2;
x % 2 ? oddFunction() : evenFunction();
Please write the following code in your console:
var isEven = function(deep) {
if (deep % 2 === 0) {
return true;
}
else {
return false;
}
};
isEven(44);
Please Note: It will return true, if the entered number is even otherwise false.
Use Modulus, but.. The above accepted answer is slightly inaccurate. I believe because x is a Number type in JavaScript that the operator should be a double assignment instead of a triple assignment, like so:
x % 2 == 0
Remember to declare your variables too, so obviously that line couldn't be written standalone. :-) Usually used as an if statement. Hope this helps.
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
array.each { |x| puts x if x % 2 == 0 }
ruby :D
2
4
6
8
10
/**
* #param {number} x
* #return {boolean}
*/
var isPalindrome = function(x) {
var y=x,num=0,rem;
while(x>0)
{
rem=x%10;
num=(num*10)+rem;
x=x/10;
}
if(num==y)
return true;
else
return false ;
};
I am still getting wrong output as false but my logic is correct.
This is leetcode palindrome question i am trying it with javascript logic is correct but still not able to figure it out.
There is just one issue:
In JavaScript numbers are floating point numbers by default, and so / performs a floating point division. You need to truncate that:
x = Math.floor(x / 10);
A remark on your code:
The construct if (boolean) return true; else false is an anti-pattern. Since boolean already represents the value you want to return, you should just return it. So in your case do:
return num == y;
Your logic seems fine but execution is having some minor errors. Please use below snippet, it should work:
var isPalindrome = function(x) {
if (x < 0) {
return false;
}
// Store the number in a variable
let number = x;
// This will store the reverse of the number
let reverse = 0;
while (number > 0) {
reverse = reverse * 10 + number % 10;
number = parseInt(number / 10);
}
return x === reverse;
}
I am creating a function that returns whether the passed in number is odd Without the modulo operator. The tricky part is that it should work for NEGATIVE numbers and ZERO.
here's my codes so far:
function testodd(num) {
return (num/2)*2==num;
}
var output = testodd(17);
console.log(output); // --> true
Am I making some mistakes here? Or is there a better way to do this?
you can use Bitwise operator and get same result. does this help.
<script type="text/javascript">
function oddOrEven(x) {
return ( x & 1 ) ? "odd" : "even";
}
console.log(oddOrEven(10));
</script>
For more detail about bitwise operator
Hi you can do it with bitwise AND (&) operator to check if a number is even or odd.
function testodd(num) {
if((num & 1) == 0){
return true
}
return false;
}
var output = testodd(17);
console.log(output); // --> false
var output = testodd(-16);
console.log(output); // --> true
var output = testodd(0);
console.log(output); // --> true
Try a bit-wise operation
function testodd(num) {
return num & 1; // num AND 0x1 checks for the least significant bit, indicating true or falsey
}
Remove the decimal part after division using Math.floor.
Math.floor(num / 2) * 2 === num;
For even numbers, there is no loss in decimal value. For odd numbers, decimal point value will be lost and comparison will falsy.
Here is a horribly inefficient method using recursion:
function checkOdd(num)
{
num = Math.abs(num);
if(num==0)
return false;
else if(num==1)
return true;
else
return checkOdd(num-2);
}
Of course you should never use it.
Since there's already an answer I will show you an alternative away of doing it with regex
function checkOdd(num){
console.log(/^\d*[13579]$/.test(num));
}
checkOdd(105);
Would only work with reasonably sized integers
Try
function testodd(num){
if num < 0{
var number = -num
}
int i = 1;
int product = 0;
while (product <= num)
{
product = divisor * i;
i++;
}
// return remainder
return num - (product - divisor);
}
Use this function to check if a number is odd or even, without using the modulo operator %. This should work for negative numbers and zero.
function checkOdd(num) {
// your code here
if(num<0){ //Check if number is negative
num=-num; //Convert it into positive number
}
let b=Math.floor(num/2) //Taking value for loop iteration
for(var i=1;i<=b;i++){
num=num-2; //Will check the number is odd if it subtraction end to 1 by decrementing -2 to the number
if(num==1){
return true; //return true if number is odd
}
}
return false; //return false if number is even
}
You can use isInteger method
function isEven(n){
return Number.isInteger(n / 2);
}
function odd(num) {
if (num === 0) {
return false;
}
num = Math.abs(num);
while (num >= 2) {
num = num - 2;
}
if (num === 1) {
return true;
} else {
return false;
}
}
Even number
lets take an even number say 6;
6 divided by 2 is 3;
Math.round(3) is 3;
Math.floor(3) is 3;
3===3 eveluates to true so 6 is an even number;
Odd number
lets take an odd number say 9;
9 divided by 2 is 4.5;
Math.round(4.5) is 5;
Math.floor(4.5) is 4;
5===4 evaluates to false so 9 is an odd number;
function evenChecked(num) {
if (Math.round(num / 2) === Math.floor(num / 2)) {
return `${num} is even`;
} else {
return `${num} is odd`;
}
}
console.log(evenChecked(23));
console.log(evenChecked(90));
console.log(evenChecked(56));
console.log(evenChecked(49));
I have a piece of code (which I believe is very inefficient and bad; I may be wrong though.), that checks whether a variable is in range determined by some other variables, like so;
if ((a >= (x.eq(0) && y.eq(0)) || (a >= x.eq(1) && y.eq(1)) ... || (a >= x.eq(n) && y.eq(n)))) {
// code here
}
(I might have gotten the amount of brackets wrong in the question, but the code itself works.)
where n is the total amount of numbers in arrays x and y.. Obviously, the if condition looks very, very large and I believe it's unoptimized and "bad".
Is there anything I can use to make the condition shorter? In case the block above is unreadable, what I want in pseudocode:
Check if a is between x(0) and y(0).
If true, do things.
Else check if a is between x(1) and y(1).
If true, do things.
Else check ... if a is between x(n) and y(n).
If true, do things.
Else do nothing.
You could use a for loop and exit if one condition is met. You need to use the right comparison for a range chekc with a and the left and right border.
var i;
for (i = 0; i <= n; i++) {
if (x.eq(i) <= a && a <= y.eq(i)) {
// do something
break;
}
}
Assuming you have two arrays with the corresponding length, or just one with an object with x and y property, you could use Array#some
array.some(function (o, i) {
if (o.x <= a && a <= o.y) {
// do something
// update(o, i);
return true; // exit iteration
}
});
You can create a reusable function which makes a range of numbers and checks if your condition is met:
// usage:
// isBetweenAny
// (0,10) // start and end of range
// (x, y) // functions, in your case in question pass x.eq and y.eq
// (a) // your 'a' value
// returns true or false
const isBetweenAny = (startNum, endNum) => (x, y) => a =>
[...Array(endNum + 1).keys()].slice(startNum) // range of numbers (inclusive)
.some(num => (a >= x(num) && a <= y(num))) // if any number satisfies the condition
// identity function - for easy testing
const map = x => x;
const res1 = isBetweenAny(1, 10)(map, map)(1) // true: 1 in [0...10] range
const res2 = isBetweenAny(2, 10)(map, map)(1) // false: 1 not in [2...10] range
console.log(res1, res2)
Then you can also use it like this:
const mySpecificCase = isBetweenAny(0, 100)(x.eq, y.eq) // new function for your specific case
if (mySpecificCase(a)) {
....
}
Do you want something like this?
// try every number between 0 and n
for (var i = 0; i++, i < n) {
// generic version of your condition
if (a >= (x.eq(i) && y.eq(i)) {
// do the things
break; // break the loop so the things are only done once
}
}
How do I figure out if a variable is divisible by 2? Furthermore I need do a function if it is and do a different function if it is not.
Use modulus:
// Will evaluate to true if the variable is divisible by 2
variable % 2 === 0
Seriously, there's no jQuery plugin for odd/even checks?
Well, not anymore - releasing "Oven" a jQuery plugin under the MIT license to test if a given number is Odd/Even.
Source code is also available at http://jsfiddle.net/7HQNG/
Test-suites are available at http://jsfiddle.net/zeuRV/
(function() {
/*
* isEven(n)
* #args number n
* #return boolean returns whether the given number is even
*/
jQuery.isEven = function(number) {
return number % 2 == 0;
};
/* isOdd(n)
* #args number n
* #return boolean returns whether the given number is odd
*/
jQuery.isOdd = function(number) {
return !jQuery.isEven(number);
};
})();
You don't need jQuery. Just use JavaScript's Modulo operator.
You can use the modulus operator like this, no need for jQuery. Just replace the alerts with your code.
var x = 2;
if (x % 2 == 0)
{
alert('even');
}
else
{
alert('odd')
}
You can do it in a better way (up to 50 % faster than modulo operator):
odd: x & 1
even: !(x & 1)
Reference: High Performance JavaScript, 8. ->Bitwise Operators
You can also:
if (x & 1)
itsOdd();
else
itsEven();
if (x & 1)
itIsOddNumber();
else
itIsEvenNumber();
Hope this helps.
let number = 7;
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
Here is a complete function that will log to the console the parity of your input.
const checkNumber = (x) => {
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
}
var x = 2;
x % 2 ? oddFunction() : evenFunction();
Please write the following code in your console:
var isEven = function(deep) {
if (deep % 2 === 0) {
return true;
}
else {
return false;
}
};
isEven(44);
Please Note: It will return true, if the entered number is even otherwise false.
Use Modulus, but.. The above accepted answer is slightly inaccurate. I believe because x is a Number type in JavaScript that the operator should be a double assignment instead of a triple assignment, like so:
x % 2 == 0
Remember to declare your variables too, so obviously that line couldn't be written standalone. :-) Usually used as an if statement. Hope this helps.
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
array.each { |x| puts x if x % 2 == 0 }
ruby :D
2
4
6
8
10