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

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
}

Related

Javascript Serial Number CoderByte problem

I'm currently solving a problem at CoderByte. Here's the scenario.
Have the function SerialNumber(str) take the str parameter being passed and determine if it is a valid serial number with the following constraints:
It needs to contain three sets each with three digits (1 through 9) separated by a period.
The first set of digits must add up to an even number.
The second set of digits must add up to an odd number.
The last digit in each set must be larger than the two previous digits in the same set.
If all the above constraints are met within the string, the your program should return the string true, otherwise your program should return the string false. For example: if str is "224.315.218" then your program should return "true".
Examples
Input: "11.124.667"
Output: false
Input: "114.568.112"
Output: true
Here's my JS code for this problem.
function SerialNumber(str) {
// code goes here
if(str.length < 11) {
return "false";
}
for (let x = 0; x < str.length; x++) {
if(str[x] === '0') {
return "false";
}
}
const first = str[0] + str[1] + str[2];
const second = str[4] + str[5]+ str[6];
if (first % 2 !== 0 || second % 2 === 0) {
return "false";
}
if (str[2] < str[1] || str[2] < str[0] || str[6] < str[5] || str[6] < str[4] || str[10] < str[8] || str[10] < str[9]) {
return "false";
} else {
return "true";
}
}
console.log("11.124.667 : " + SerialNumber("11.124.667"));
console.log("114.568.112 : " + SerialNumber("114.568.112"));
When I input "11.124.667", it will return to false (which is correct). And when I input "114.568.112", it will also return to false (which is not correct). Any tips on how can I obtain this? Thanks for the feedback.
I tried your code and the problem comes from the third return false for the 2nd example, when you set second, you concatenate strings instead of adding numbers, thus %2 is always equal to 0 since
I added console.log before each return false to see which condition failed.
Here's the fixed code in which I added parseInt for first and second
function SerialNumber(str) {
if (str.length < 11) {
console.log("first")
return "false";
}
for (let x = 0; x < str.length; x++) {
if (str[x] === '0') {
console.log("second")
return "false";
}
}
const first = parseInt(str[0]) + parseInt(str[1]) + parseInt(str[2]);
const second = parseInt(str[4]) + parseInt(str[5]) + parseInt(str[6]);
if (first % 2 !== 0 || second % 2 === 0) {
console.log("third")
return "false";
}
if (str[2] < str[1] || str[2] < str[0] || str[6] < str[5] || str[6] < str[4] || str[10] < str[8] || str[10] < str[9]) {
console.log("fourth")
return "false";
} else {
return "true";
}
}
console.log("11.124.667 : " + SerialNumber("11.124.667"));
console.log("114.568.112 : " + SerialNumber("114.568.112"))

How to get the max occurrences of a number in an array

as answer to an exercise in which I had to create a function that given an array of numbers return the number with most occurrences, and if more than one number had the max number of occurrences return the minor one. This is the implementation I made, but I'm pulling my hair figuring out why it return 10 instead of 9 in the example.
It appears to be evaluating 10 < 9 as true. What's wrong?
function maxOccurencies(arr) {
var aux = [], max = 0, final = null;
for (var i=0,t=arr.length; i<t; i++) {
aux[arr[i]] = (aux[arr[i]] || 0) + 1;
if (aux[arr[i]] > max) max = aux[arr[i]];
}
for (x in aux) {
if ( aux[x] == max && (x < final || final == null)) {
final = x;
}
}
return final;
}
document.write(maxOccurencies([10,10,10,9,9,9,8,7,4,5,1]));
Putting typeof(x) in your second loop reveals that some of your variables are being cast as type string! Still looking into exactly where this is occurring. You can replace
if ( aux[x] == max && (x < final || final == null)) {
with
if ( aux[x] == max && (parseInt(x) < parseInt(final) || final == null)) {
to return the correct value of 9.
Edit:
Very interesting, I was unaware of Javascript's exact handling of arrays in for...in loops. See the following other questions for more information:
JavaScript For-each/For-in loop changing element types
Why is using “for…in” with array iteration such a bad idea?
Also note that you can use arr.forEach(function(element){...}); and the elements are returned with their types intact.
I think the problem is just that the x in aux is not a number so the if statement isn't evaluating correctly. when converted to a number then it returns 9 (below).
(3 == 3 && ("10" < "9" || "9" == null)) evaluates to true
function maxOccurencies(arr) {
var aux = [], max = 0, final = null;
for (var i=0,t=arr.length; i<t; i++) {
aux[arr[i]] = (aux[arr[i]] || 0) + 1;
if (aux[arr[i]] > max) max = aux[arr[i]];
}
for (x in aux) {
if ( aux[x] == max && (parseInt(x) < final || final == null)) {
final = parseInt(x);
}
}
return final;
}
document.write(maxOccurencies([10,10,10,9,9,9,8,7,4,5,1]));
"I'm pulling my hair figuring out why it return 10 instead of 9 in the example."
That's because in this sort of comparison, 10 is smaller than 9,8,7,6,5,4,3, 2 but a bit grater than 1.
:)
This small type correction will fix it:
function maxOccurences(arr) {
aux = [], max = 0, final = null;
for (var i=0,t=arr.length; i<t; i++) {
aux[arr[i]] = (aux[arr[i]] || 0) + 1;
if (aux[arr[i]] > max) max = aux[arr[i]];
}
for (x in aux) {
if ( aux[x] == max && (+x < final || final == null)) {
final = x;
}
}
return final;
}

Sort empty or null to bottom always

The following is a natural sort function I pulled from somewhere I forget exactly. I'm looking to modify it so that empty or null values always sort to the bottom regardless of asc/desc.
Here is what I have right now:
function gridNaturalSorter(a, b) {
if(a[sortcol])
a = a[sortcol].replace(/<(?:.|\n)*?>/gm, '');
if(b[sortcol])
b = b[sortcol].replace(/<(?:.|\n)*?>/gm, '');
if(b)
b = b.toString().substr(0, 15);
if(a)
a = a.toString().substr(0, 15);
var re = /(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi,
sre = /(^[ ]*|[ ]*$)/g,
dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
hre = /^0x[0-9a-f]+$/i,
ore = /^0/,
i = function(s) {
return gridNaturalSorter.insensitive && (''+s).toLowerCase() || ''+s
},
// convert all to strings strip whitespace
x = i(a).replace(sre, '') || '',
y = i(b).replace(sre, '') || '',
// chunk/tokenize
xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
// numeric, hex or date detection
xD = parseInt(x.match(hre)) || (xN.length != 1 && x.match(dre) && Date.parse(x)),
yD = parseInt(y.match(hre)) || xD && y.match(dre) && Date.parse(y) || null,
oFxNcL, oFyNcL;
// first try and sort Hex codes or Dates
if (yD)
if ( xD < yD ) return -1;
else if ( xD > yD ) return 1;
// natural sorting through split numeric strings and default strings
for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
// find floats not starting with '0', string or 0 if not defined (Clint Priest)
oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
// handle numeric vs string comparison - number < string - (Kyle Adams)
if (isNaN(oFxNcL) !== isNaN(oFyNcL)) {
return (isNaN(oFxNcL)) ? 1 : -1;
}
// rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
else if (typeof oFxNcL !== typeof oFyNcL) {
oFxNcL += '';
oFyNcL += '';
}
if (oFxNcL < oFyNcL)
return -1;
if (oFxNcL > oFyNcL)
return 1;
}
return 0;
}
If you know how to implement multiple comparators and a comparator that sorts null to bottom that's quite easy.
To implement multiple comparators, you just have to return the result of the first comparator that doesn't return 0.
Here I also created a withComparators helper function that allows to compose multiple comparators together. If you understand this code you will be able to easily come up with your own solution for your specific problem.
Note that your gridNaturalSorter function is a comparator just like nullsToBottom is in my example.
E.g.
var items = ['test', null, 'test1', 'test3', null, 'test4'];
items.sort(withComparators(nullsToBottom, textAsc));
//["test", "test1", "test3", "test4", null, null]
function nullsToBottom(a, b) {
return a === b? 0 : a === null? 1 : -1;
}
function textAsc(a, b) {
return a < b? -1 : +(a > b);
}
function withComparators() {
var comparators = arguments;
return function (a, b) {
var len = comparators.length, i = 0, result;
for (; i < len; i++) {
result = comparators[i](a, b);
if (result) return result;
}
return 0;
};
}

Best way to check if a character is a number of letter in javascript?

In javascript whats the best way to check if a character (length 1), is a number (i.e. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9) or a letter (i.e. A to Z, a to z)?
Thanks
Why not:
function isNumber(i) {
return (i >= '0' && i <= '9');
}
function isLetter(i) {
return ((i >= 'a' && i <= 'z') || (i >= 'A' && i <= 'Z'));
}
I wrote a little test case for you, at least for the numeric checking function.
Considering the fact that all functions returns true with either a numberic 1 or a string '1' literal, using an Array seems to be the fastest way (at least in Chrome).
var isNumericChar = (function () {
var arr = Array.apply(null, Array(10)).map(function () { return true; });
return function (char) { return !!arr[char]; };
})();
However, if you accept that it might return false for 1, the switch statement is then significantly faster.
Try this.
function validate_string() {
var str = "a"; //change to desired value;
var regX = new RegExp("([0-9A-Za-z])");
var ans = false;
if(str.length == 1) {
ans = regX.test(str);
}
return ans;
}
Edit: Refactored my answer.
function validateString(char) {
let regx = new RegExp(/^[0-9A-Za-z]{1}$/g);
return regx.test(char);
}
validateString('4'); // true
validateString('as'); // false
validateString(''); // false
validateString(); // false
Maybe try something like this
var sum = 0; //some value
let num = parseInt(val); //or just Number.parseInt
if(!isNaN(num)) {
sum += num;
}
This blogpost sheds some more light on this check if a string is numeric in Javascript | Typescript & ES6
You can check for the type of the variable
function checkType(input){
console.log(typeof input)
}
checkType(1234); //number
checkType('Hello') //string
Here is an updated version
function checkType(i){
var input = i.toString(); //convert everything to strings to run .lenght() on it
for(var i=0; i<input.length; ++i){
if(input[i] >= '0' && input[i] <= '9'){
console.log(input[i]+' is a number');
}else if((input[i] >= 'a' && input[i] <= 'z') || (input[i] >= 'A' && input[i] <= 'Z')){
console.log(input[i]+' is a letter');
}
}
}
checkType('aa9fgg5')

Testing whether a value is odd or even

I decided to create simple isEven and isOdd function with a very simple algorithm:
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.
// Returns true if:
//
// n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string
(function (global) {
function basicTests(n) {
// Deal with empty string
if (n === '')
return false;
// Convert n to Number (may set to NaN)
n = Number(n);
// Deal with NaN
if (isNaN(n))
return false;
// Deal with infinity -
if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
return false;
// Return n as a number
return n;
}
function isEven(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Convert to Number and proceed
n = Number(n);
// Return true/false
return n === 0 || !!(n && !(n%2));
}
global.isEven = isEven;
// Returns true if n is an integer and (n+1) is even
// Returns false if n is not an integer or (n+1) is not even
// Empty string evaluates to zero so returns false (zero is even)
function isOdd(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Return true/false
return n === 0 || !!(n && (n%2));
}
global.isOdd = isOdd;
}(this));
Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?
There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript.
Use modulus:
function isEven(n) {
return n % 2 == 0;
}
function isOdd(n) {
return Math.abs(n % 2) == 1;
}
You can check that any value in Javascript can be coerced to a number with:
Number.isFinite(parseFloat(n))
This check should preferably be done outside the isEven and isOdd functions, so you don't have to duplicate error handling in both functions.
I prefer using a bit test:
if(i & 1)
{
// ODD
}
else
{
// EVEN
}
This tests whether the first bit is on which signifies an odd number.
How about the following? I only tested this in IE, but it was quite happy to handle strings representing numbers of any length, actual numbers that were integers or floats, and both functions returned false when passed a boolean, undefined, null, an array or an object. (Up to you whether you want to ignore leading or trailing blanks when a string is passed in - I've assumed they are not ignored and cause both functions to return false.)
function isEven(n) {
return /^-?\d*[02468]$/.test(n);
}
function isOdd(n) {
return /^-?\d*[13579]$/.test(n);
}
Note: there are also negative numbers.
function isOddInteger(n)
{
return isInteger(n) && (n % 2 !== 0);
}
where
function isInteger(n)
{
return n === parseInt(n, 10);
}
Why not just do this:
function oddOrEven(num){
if(num % 2 == 0)
return "even";
return "odd";
}
oddOrEven(num);
To complete Robert Brisita's bit test .
if ( ~i & 1 ) {
// Even
}
var isOdd = x => Boolean(x % 2);
var isEven = x => !isOdd(x);
var isEven = function(number) {
// Your code goes here!
if (number % 2 == 0){
return(true);
}
else{
return(false);
}
};
A few
x % 2 == 0; // Check if even
!(x & 1); // bitmask the value with 1 then invert.
((x >> 1) << 1) == x; // divide value by 2 then multiply again and check against original value
~x&1; // flip the bits and bitmask
We just need one line of code for this!
Here a newer and alternative way to do this, using the new ES6 syntax for JS functions, and the one-line syntax for the if-else statement call:
const isEven = num => ((num % 2) == 0);
alert(isEven(8)); //true
alert(isEven(9)); //false
alert(isEven(-8)); //true
A simple modification/improvement of Steve Mayne answer!
function isEvenOrOdd(n){
if(n === parseFloat(n)){
return isNumber(n) && (n % 2 == 0);
}
return false;
}
Note: Returns false if invalid!
Different way:
var isEven = function(number) {
// Your code goes here!
if (((number/2) - Math.floor(number/2)) === 0) {return true;} else {return false;};
};
isEven(69)
Otherway using strings because why not
function isEven(__num){
return String(__num/2).indexOf('.') === -1;
}
if (testNum == 0);
else if (testNum % 2 == 0);
else if ((testNum % 2) != 0 );
Maybe this?
if(ourNumber % 2 !== 0)
var num = someNumber
isEven;
parseInt(num/2) === num/2 ? isEven = true : isEven = false;
for(var a=0; a<=20;a++){
if(a%2!==0){
console.log("Odd number "+a);
}
}
for(var b=0; b<=20;a++){
if(b%2===0){
console.log("Even number "+b);
}
}
Check if number is even in a line of code:
var iseven=(_)=>_%2==0
This one is more simple!
var num = 3 //instead get your value here
var aa = ["Even", "Odd"];
alert(aa[num % 2]);
To test whether or not you have a odd or even number, this also works.
const comapare = x => integer(checkNumber(x));
function checkNumber (x) {
if (x % 2 == 0) {
return true;
}
else if (x % 2 != 0) {
return false;
}
}
function integer (x) {
if (x) {
console.log('even');
}
else {
console.log('odd');
}
}
Using modern javascript style:
const NUMBERS = "nul one two three four five six seven ocho nueve".split(" ")
const isOdd = n=> NUMBERS[n % 10].indexOf("e")!=-1
const isEven = n=> isOdd(+n+1)
function isEven(n) {return parseInt(n)%2===0?true:parseInt(n)===0?true:false}
when 0/even wanted but
isEven(0) //true
isEven(1) //false
isEven(2) //true
isEven(142856) //true
isEven(142856.142857)//true
isEven(142857.1457)//false
​
if (i % 2) {
return odd numbers
}
if (i % 2 - 1) {
return even numbers
}

Categories

Resources