Mind has gone blank this afternoon and can't for the life of me figure out the right way to do this:
if(i!="3" && i!="4" && i!="5" && i!="6" && i!="7" && i!="8" && i!="9" && i!="2" && i!="19" && i!="18" && i!="60" && i!="61" && i!="50" && i!="49" && i!="79" && i!="78" && i!="81" && i!="82" && i!="80" && i!="70" && i!="90" && i!="91" && i!="92" && i!="93" && i!="94"){
//do stuff
}
All those numbers need to be in an array, then I can check to see if "i" is not equal to any 1 of them.
var a = [3,4,5,6,7,8,9];
if ( a.indexOf( 2 ) == -1 ) {
// do stuff
}
indexOf returns -1 if the number is not found. It returns something other than -1 if it is found. Change your logic if you want.
Wrap the numbers in quotes if you need strings ( a = ['1','2'] ). I don't know what you're dealing with so I made them numbers.
IE and other obscure/older browsers will need the indexOf method:
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
My mind made this solution:
function not(dat, arr) { //"not" function
for(var i=0;i<arr.length;i++) {
if(arr[i] == dat){return false;}
}
return true;
}
var check = [2,3,4,5,6,7,8,9,18,19,49,50,60,61,70,78,79,80,81,82,90,91,92,93,94]; //numbers
if(not(i, check)) {
//do stuff
}
This solution is cross-browser:
var valid = true;
var cantbe = [3, 4, 5]; // Fill in all your values
for (var j in cantbe)
if (typeof cantbe[j] === "number" && i == cantbe[j]){
valid = false;
break;
}
valid will be true if i isn't a 'bad' value, false otherwise.
Related
I have the following data:
I basically want the 5,6,7 records to be at the very top of the list ordered by eta. The rest I am OK with as they stand. since they do not realy have an eta.
My JS function :
bubbleSortETA : function(array) {
var swapped;
do {
swapped = false;
for(var i = 0; i < array.length; i++) {
console.log('array[i]');
console.log(array[i]);
console.log('array[i+1]');
console.log(array[i+1]);
var thisRowEta;
var nextRowEta;
if (array[i] && typeof(array[i].eta) != "undefined"){
thisRowEta = array[i].eta;
}else{
thisRowEta = 1000; //so it appears at the bottom???
}
if (array[i+1] && typeof(array[i+1].eta) != "undefined"){
nextRowEta = array[i+1].eta;
}else{
nextRowEta = 1000;
}
if(array[i] && array[i + 1] && typeof(array[i].walkInDetails) != "undefined" && typeof(array[i+1].walkInDetails) != "undefined" && (thisRowEta != nextRowEta)){
this.swap(array, i, i + 1);
console.log('we swapped...');
swapped = true;
}
}
} while(swapped);
console.log(array);
return array;
}
It goes into this never ending loop. I have tried looking at output statements but am unable to understand why it is going into infinite loop.
Any tips?
How to implement this valid function?
I want to implement a test function that returns true or false,
example : 'any-string-1'.valid('!empty'):
this is my valid.js file
function valid(str) {
if (
typeof str == "undefined" ||
!str ||
str === "" ||
str.length < 10 ||
!/[^\s]/.test(str) ||
/^.*-s/i.test(str)
) {
return true;
} else if (str.length > 30) {
return false;
}
}
module.exports = valid;
Assuming you are using Jest, you can use toBe:
const emptyStr = '';
const str = 'some-str';
expect(Boolean(emptyStr.length)).toBe(false); // it's empty, it's false because length is 0;
expect(str.length > 30).toBe(false); // it's false because length is not greather than 30;
expect(str.length < 10).toBe(true); // it's true because length is lower than 10;
I'm a javascript beginner doing some CodeWars.com questions. I came across this question and I'm stuck due to a "cannot read property length null" error. I've tried to look up that error and can't find what the problem is in my program.
The assignment is:
"Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The string can contains any char."
And this is what I've written so far:
function XO(str) {
var x = "x";
var o = "o";
var numX = str.match(/x/gi).length;
var numO = str.match(/o/gi).length;
while(str.indexOf(x) > -1 || str.indexOf(o) > -1) {
if(numX == numO){
return true;
}
}
if (numX === -1 && numO === -1){
return true;
}
}
XO("xoxo");
The assignment also says that if there is neither an X or an O then the program should return true.
This will not give you that error. When there are no matches, the match function returns null and you cannot get the length of null. A few extra lines solves this issue.
function XO(str) {
var x = "x";
var o = "o";
var numX = 0;
var numO = 0;
var xMatch = str.match(/x/gi);
var oMatch = str.match(/o/gi);
if (xMatch) {
numX = xMatch.length;
}
if (oMatch) {
numO = oMatch.length;
}
while(str.indexOf(x) > -1 || str.indexOf(o) > -1) {
if(numX == numO){
return true;
} else {
return false;
}
}
if (numX === -1 && numO === -1){
return true;
} else {
return false;
}
}
console.log(XO("ddd"));
I think you are making this problem more complex than it has to be.
All you need to do is make the string lowercase(to account for case insensitive), traverse the string, and when it finds an x, add 1 to a counter, and when you find and o, decrease 1 from the counter.
If it ends at 0, you return true, else you return false. There's no need for regexes
function XO(str){
var count = 0;
str = str.toLowerCase();
for(var i = 0; i < str.length; i++){
if(str[i] === 'x') count++;
if(str[i] === 'o') count--;
}
return count === 0 ? true : false;
}
Yes you have to check the return value of match is not null before checking the length property. However
while(str.indexOf(x) > -1 || str.indexOf(o) > -1) {
if(numX == numO){
return true;
}
}
looks like an infinite loop if either string contains lower case 'x' or 'o' and there are a different number of each.
More simply:
function XO(str)
{ var matchX = str.match(/x/gi);
var matchY = str.match(/o/gi);
return (matchX && matchY) ? matchX.length == matchY.length : !matchX && !matchY;
}
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;
};
}
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
}