Check whether three given integer values are in the range 50..99 - javascript

I want to create a function to check 3 values.
If the 3 values are in the range 50..99, I return true, otherwise false.
In this example, normally the answer is false.
console.log(check_three_nums(65, 9, 199));
I have as answer true.
I don't understand, why?
function check_three_nums(x, y, z) {
if ((x >= 50 && x <= 99) || (y >= 50 && y <= 99) || (z >= 50 && z <= 99)) {
return true;
} else {
return false;
}
}
// console.log(check_three_nums(50, 90, 99));
// console.log(check_three_nums(5, 9, 199));
// console.log(check_three_nums(65, 89, 199));
console.log(check_three_nums(65, 9, 199));

You can use this function to check any amount of number.
function check(...args) {
for (let a of args) {
if (a < 50 || a > 99)
return false
}
return true
}

The double pipe operator (||) means OR, your function is currently returning true if at least one of the param is in your range.
Try to change it whith the '&&' operator
It should work as expected
function check_three_nums(x, y, z) {
if ((x >= 50 && x <= 99) && (y >= 50 && y <= 99) && (z >= 50 && z <= 99)) {
return true;
} else {
return false;
}
}
// console.log(check_three_nums(50, 90, 99));
// console.log(check_three_nums(5, 9, 199));
// console.log(check_three_nums(65, 89, 199));
console.log(check_three_nums(65, 9, 199));

"or operator" (||) will output true if one of the parameter values ​​is true (condition1 is true or condition2 is true). You can use the "and operator" (&&), this operator will only output true if both parameter values ​​are true (condition1 and condition2 are true)

Related

Multiple and different conditions in Javascript

I have a problem with logic.
If the number is higher than 0 and less than 10 AND the number is 11 AND the number is 22 do something. (1, 2, 3, 4, 5, 6, 7, 8, 9, 11 or 22).
And ELSE IF the number is higher than 10 BUT is NOT 11 or is NOT 22, do something else. (10, 12, 13 ....20, 21, 23, 24...)
I got to do only with 11, but I have no clue how to insert another condition with 22.
if (n >= 0 && n < 10) || (n == 11 && n == 22) {
do something
} else if (n >= 10 && n != 11) && (n != 22) {
do something else
}
Try (n >= 1 && n <= 9) || n == 11 || n == 22 which will check if the number is between 1 and 9 inclusive (1 to 9) OR it's 11 OR it's 22.
Then, in your else if, just check for >= 10 - numbers less than 1 e.g. 0, won't trigger the else either.
if ((n >=1 0 && n <= 9) || n == 11 || n == 22) {
do something
} else if (n >= 10) {
do something else
}
Use >= and <= to make it clearer what values you're looking for otherwise it takes a little extra mental load to realise that n > 0 && n < 10 really means values 1 to 9.
Also, it's JavaScript and numbers can either be integral or floating point, so greater than zero could be 0.1 etc.
In your if statement, you say:
n is larger or equal to 0 AND n is smaller than 10
OR
n is equal to 11 AND n is equal to 22
Which means, the if block will run for numbers that are between 0 and 9 (inclusive) OR for the numbers 11 AND 22. So the number can either be between 0 and 9 or it can be BOTH 11 and 22, which is impossible.
My take on the if statement:
if (n >= 1 && n <= 9 || n == 11 || n == 22) {
do something;
}
That way, you don't get confused with the inclusive and exclusive numbering and make sure that either 11 or 22 is allowed.
The second block will run for numbers that are greater or equal to 10 AND not 11 AND not 22. Which is just fine.
else if (n >= 10 && n != 11 && n != 22) {
do something else;
}
In this answer, I assume you don't want to entirely skip the 10. If you do, then in the second statement, you would check for n > 10.
Logically, this is sound. However, I don't think that you need to check for 11 and 22 in the second one, as the if block will run first and if the number is 11 or 22, the first if block will run. So the second one doesn't need to account for them.
Based on your example of (1, 2, 3, 4, 5, 6, 7, 8, 9, 11 or 22) it sounds like this is what you're going for?
if ((n > 0 && n < 10) || n == 11 || n == 22) {
// do something
} else if (n >= 10) {
// do something else
}
Edit: Added else if (n >= 10) that I overlooked
Just take the comparison and because of the higher precedence of logical AND && over logical OR ||, you need no parenthesis.
if (n >= 0 && n < 10 || n === 11 || n === 22) {
// 1, 2, 3, 4, 5, 6, 7, 8, 9, 11 or 22
// do something
} else {
// 10, 12, 13 ... 21, 23 ...
// do something
}
Your first condition will never succeed because you can't have a number higher than 0 and less than 10 AND this same number is equal to 11 AND also being equal to 22 (in both case, it'll be more than 10).
if ((n > 0 && n < 10) || n == 11 || n == 22) {
// my number is 1, 2, 3, 4, 5, 6, 7, 8, 9, 11 or 22
} else {
// my number is almost everything except the values from above
}
You were almost there.
To test for 1, 2, 3, 4, 5, 6, 7, 8, 9, 11 or 22:
if (n >= 0 && n < 10) || (n == 11 && n == 22) {
Can minimally be changed to:
if ((n > 0 && n < 10) || (n == 11 || n == 22)) {
The three important changes are:
balance parentheses to make a proper if( ) construct.
>= 0 becomes > 0 to achieve the higher than zero requirement.
The last && becomes ||.
This also changes the order of operations such that we don't actually need any extra parentheses at all in this case. This also happens to be correct, and is simpler:
if (n > 0 && n < 10 || n == 11 || n == 22) {
...because && has higher precedence than || and the comparators (>, < and ==) have higher precedence than the conditionals (&& and ||).
At this point you don't need an else if condition. Just else will suffice. 11 and 22 are handled by the affirmative case of the if and therefore n will be neither of those things in the else case.
Final product:
if (n > 0 && n < 10 || n == 11 || n == 22) {
// 1, 2, 3, 4, 5, 6, 7, 8, 9, 11 or 22
} else {
// Something else. :)
}
Take a look at the documentation, don't confuse logicial AND (&&) and logical OR (||).
function check(n) {
if((n >= 1 && n <= 9) || (n == 11 || n == 22)) {
console.log(n, true);
} else if(n >= 10) {
console.log(n, false);
}
}
check(1) // true
check(11) // true
check(22) // true
check(0)
check(10) // false
check(12) // false
check(21) // false
check(23) // false

Given 2 positive int values, return the larger value that is in the range 10..20 inclusive, or return 0 if neither is in that range

My problem is that I can't seem to access the second else/if statement where I try to include a clause where if a number is still in range it should still return. The syntax is all correct, I was told my brackets are improperly placed but I can't fathom where or how.
var max1020=function(a, b) {
if ((a >= 10 && a <= 20) && (b >= 10 && b <= 20)) {
if (a > b) { //comparing my a and my b and returning greater
return a;
} else if (b > a) {
return b;
} else if ((a >= 10 && a <= 20) || (b >= 10 && b <= 20)) {
if (a >= 10 && a <=20) {
return a;
} else if (b >= 10 && b <=20) {
return b;
}
} else {
return 0;
}
}
};
You could use Math.max for it with a proper check if in range.
function range(a, b) {
function inRange(v) {
return v >= 10 && v <= 20 ? v : 0;
}
return Math.max(inRange(a), inRange(b));
}
console.log(range(-1,-5));
console.log(range(1, 5));
console.log(range(10, 5));
console.log(range(10, 15));
console.log(range(100, 15));
It seems that you're returning if a is bigger than b and if b is bigger than a. So the only time you would reach the second else if is when a = b? Maybe I missed something.
var max1020=function(a, b) {
var max = (a>b?a:b); //first find the max value of a and b
if(max>=10&&max<=20) return max; //if max is in range then at
//least on of them is in range and is bigger
else if(a>=10 && a<=20) return a; //if the max in not in range then only one could be in range so return the one that in range
else if(b>=10 && b<=20) return b;
return 0; //if you reach this point none of them was in range
};
If you take advantage of some of the new ES6 features, you can make your function shorter, simpler, and better.
function maxRange(min, max, ...values) {
values = values.filter(e => e >= min && e <= max);
return values.length ? Math.max(...values) : 0;
}
You can specify the range and you are not limited to only 2 values. You can use it like this
maxRange(10, 20, 10, 15) // Returns 15
maxRange(10, 20, 10, 15, 20, 30) // Returns 20
maxRange(10, 20, 5, 25, 99) // Returns 0
maxRange(100, 150, 99, 120, 200) // Returns 120
maxRange(-50, -20, 12, -77, 123, -24) // Returns -24
Here is a bit longer version with comments to better understand how it works.
function maxRange(min, max, ...values) { // Collects the remaining arguments in an array with the rest operator
values = values.filter(e => { // Filter the arguments. Using the arrow function
if(e >= min && e <= max) { // Test if an argument is in range
return true; // Keep it if its in range
}
else {
return false; // Discard it otherwise
}
});
if(values.length) { // Test if we have any arguments left
return Math.max(...values); // Return the highest of them. Using the spread operator
}
else {
return 0; // Return 0 if no argument was in range
}
}
Here's some more info on the features I've used
Rest Operator
Spread Operator
Arrow Function
Array Filter
Conditional (Ternary) Operator

IsNan() function considers certain kind of strings as number - node js

I'm checking for integer values in node.js using IsNaN function.
Unexpectedly, this function validates the strings like 1E267146, 1E656716 , 914E6583 to be numbers, as these strings are exponential values. Any way to work around this? In actual scenario i wont get any exponential values.
ECMA6 defines Number.isInteger as follows:
Javascript
function isInteger(nVal) {
return typeof nVal === "number" && isFinite(nVal) && nVal > -9007199254740992 && nVal < 9007199254740992 && Math.floor(nVal) === nVal;
}
but this will also accept scientific notation
console.log(isInteger(1e6));
console.log(isInteger(+"1e6"));
jsfiddle
You need to be clear as to what your definitions/expectations are.
My guess is that you may want something like this, if you are testing strings and have no limits on the max or min integer.
Javascript
function isStringNumericalInteger(testValue) {
return typeof testValue === "string" && /^[\-+]?[1-9]{1}\d+$|^[\-+]?0$/.test(testValue);
}
console.log(isStringNumericalInteger("9007199254740991"));
console.log(isStringNumericalInteger("-123216848516878975616587987846516879844651654847"));
console.log(isStringNumericalInteger("1.1"));
console.log(isStringNumericalInteger("-1.1"));
console.log(isStringNumericalInteger("1e10"));
console.log(isStringNumericalInteger("010"));
console.log(isStringNumericalInteger("0x9"));
console.log(isStringNumericalInteger(""));
console.log(isStringNumericalInteger(" "));
console.log(isStringNumericalInteger());
console.log(isStringNumericalInteger(null));
console.log(isStringNumericalInteger([]));
console.log(isStringNumericalInteger({}));
Output
true
true
false
false
false
false
false
false
false
false
false
false
false
jsfiddle
If you want to bound the range to what javascript can represent numerically as an integer then you will need to add a test for && +testValue > -9007199254740992 && +testValue < 9007199254740992
If you don't like using RegExs, you can also accomplish this with a parser. Something like this:
Javascript
function isCharacterDigit(testCharacter) {
var charCode = testCharacter.charCodeAt(0);
return charCode >= 48 && testCharacter <= 57;
}
function isStringNumericalInteger(testValue) {
var start = 0,
character,
index,
length;
if (typeof testValue !== "string") {
return false;
}
character = testValue.charAt(start);
if (character === "+" || character === "-") {
start += 1;
character = testValue.charAt(start);
}
start += 1;
length = testValue.length;
if ((length > start && character === "0") || !isCharacterDigit(character)) {
return false;
}
for (index = start; index < length; index += 1) {
if (!isCharacterDigit(testValue.charAt(index))) {
return false;
}
}
return true;
}
jsfiddle
I would use something like below code to validate number input. First I parse the given value to float and then check isNaN().
var isNumber = function (obj) {
return !isNaN(parseFloat(obj)) && isFinite(obj);
};
I think this is what you need in your case (i hate regex because this is not very good for the performance but..)
http://jsbin.com/EQiBada/1/
var NMAX = Math.pow(2, 53);
function isNumeric(n) {
n = n < 0 ? n * -1 : n;
var r = /^\d+$/.test(n);
if (r === true)
{
return parseInt(n, 10) >= (NMAX * -1) + 1 && parseInt(n, 10) <= NMAX;
}
return false;
}
Minified
var NMAX = Math.pow(2, 53);
function isNumericMin(n) {
n = n < 0 ? n * -1 : n;
return /^\d+$/.test(n) === true ? parseInt(n, 10) >= (NMAX * -1) + 1 && parseInt(n, 10) <= NMAX : false;
}
var i = '1E267146'
if(isNaN(i) || !isFinite(i) !! i=="")
{
// do stuff
}
else
{
// do stuff
}

Multiple comparison operators in a JavaScript boolean expression

I'm trying to check whether the variable y is less than x and greater than z, but this boolean expression is returning false for some reason. Does JavaScript allow boolean expressions to be written concisely like this? If so, what is the correct syntax?
x = 2;
y = 3;
z = 4;
if(x > y > z){
alert("x > y > z"); //Nothing happens!
}
Try using the logical and operator:
if (x > y && y > z) {
to guarantee both conditions are true.
DEMO: http://jsfiddle.net/3sxvy/
If you need to put this into a function, you could try:
function compareNumbers(direction) {
var inOrder = (function () {
if (direction === "desc") {
return function (current, before) {
return current <= before;
};
} else if (direction === "asc") {
return function (current, before) {
return current >= before;
};
}
})();
var valid = true;
for (var i = 2; i < arguments.length; i++) {
if (!inOrder(arguments[i], arguments[i-1])) {
valid = false;
break;
}
}
return valid;
}
if (compareNumbers("desc", 33, 5)) {
console.log("Good");
} else {
console.log("Bad");
}
DEMO: http://jsfiddle.net/kn6M4/1/
Change your test to
if (x > y && y > z){
When you write (x > y > z), this is equivalent to ((x>y)>z), so you're comparing a boolean (x>y) to z. In this test, true is converted to 1, which isn't greater than 2.
You want
if(x > y && y > z){
alert("x > y > z"); //Nothing happens!
}
Javascript will try to parse your original statement from left to right and you'll end up comparing z to a boolean value which will then be parsed to a number (0 or 1).
So your original statement is equivalent to
if( (x > y && 1 > z) || (x <= y && 0 > z))

Multiple Logical Operators in javascript

I want to check the following
1: Is x a number
2. If x is less that 5 or greater than 15, sound alert
3. If all is ok, callMe()
var x = 10;
if (isNaN(x) && ((x < 5) || (x > 15))) {
alert('not allowed')
}
else
{
callMe();
}
What am I doing wrong?
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
alert('not allowed')
}
else
{
callMe();
}
This way, if x is not a number you go directly to the alert. If it is a number, you go to the next check (is x < 5), and so on.
All the other answers about the && vs || are correct, I just wanted to add another thing:
The isNaN() function only checks whether the parameter is the constant NaN or not. It doesn't check whether the parameter is actually number or not. So:
isNaN(10) == false
isNaN('stackoverflow') == false
isNaN([1,2,3]) == false
isNaN({ 'prop' : 'value'}) == false
isNaN(NaN) == true
In other words, you cannot use it to check whether a given variable contains a number or not. To do that I'd suggest first running the variable through parseInt() or parseFloat() depending on what values you expect there. After that check for isNaN(), because these functions return only numbers or NaN. Also this will make sure that if you have a numeric string then it is also treated like a number.
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
alert('not allowed')
}
else
{
callMe();
}

Categories

Resources