pattern match failure in if condition - javascript

Trying to optimise pattern matching code. Old code has few patterns which were matched against an Id coming from the callback data.
var Id = callbackData.Id
var pattern1 = /gen/g;
var pattern2 = /0--google/g;
var pattern3 = /mail/g;
var isPattern1 = pattern1.test(Id)
var isPattern2 = pattern2.test(Id)
var isPattern3 = pattern3.test(Id)
if(Id && Id !== 0 && !isPattern1 && !isPattern2 && !isPattern3)
{
//return statement
// function
} else {
//return statement
//function
}
To optimise it I have created a json file which consists the patterns. Pattern are being read from the json file and matched with the Id.
Json file : test.json
{
"PatternToSearch": {
"pattern1" : "gen",
"pattern2" : "^0--google",
"pattern3" : "mail"
}
}
var patternToMatch = require('test.json');
var patternArray = [];
Object.keys(patternToMatch.PatternToSearch).forEach(function (key) {
var value = PatternToMatch.PatternToSearch[key];
patternArray.push(value);
});
return Promise.all(patternArray);
.then(patternArrayResult => {
for (var val in patternArrayResult) {
var pattern = patternArrayResult[val];
var patternToCompare = new RegExp(pattern);
var isPattern = patternToCompare.test(Id);
}
})
I tried forEach as well but I am returning boolean value from the function and forEach doesn't return any value so I used for...in
not able to replicate this condition Id && Id !== 0 && !isPattern1 && !isPattern2 && !isPattern3. How to do it?
Tried
if(isPattern){
if(Id && Id !==0 && isPattern) {
// return statement
}
}
but this condition doesn't work when all the patterns don't match with Id. As I am this inside for loop only once this
condition will be true and other times false which takes the controller in else loop
How to replicate the condition? (Id && Id !== 0 && !isPattern1 && !isPattern2 && !isPattern3)

This is a job for some, which returns true if any item in an array causes a given function to return a truthy value:
return patternArray.some(v=>RegExp(v).test(Id));
And to include the value of Id in the test as well:
return Id && patternArray.some(v=>RegExp(v).test(Id));
You don't need to separately test Id !== 0 because a zero value will already be treated as falsy value, causing the && to short-circuit early. (So, Id && Id !== 0 will only ever produce 0 or true: execution flow cannot ever reach the condition Id !== 0 when that condition would be false, because the test Id for a zero value would have already terminated the && flow early.)

Related

How do I open an alert window if the new value is duplicated in the existing value in JS?

Here, there is a global variable. (An array type)
var obj = [];
Gets the value entered in input.
var d_idx = $('#d_idx').val();
var d_firstDate = $('#firstDate').val();
var d_secondDate = $('#secondDate').val();
var chozyintime = $('#ri_chozyinTime').val();
var zaezyintime = $('#ri_zaezyinTime').val();
"chozyintime" and "zaezyintime" are declared as arrays.
Because you can input multiple values.
var chozyinArray = [chozyintime];
var zaezyinArray = [zaezyintime];
At this time, I gave the condition. I will explain it later.
first,
if(obj.length <= 0)
{
firstAddData(d_idx, d_firstDate, d_secondDate, chozyinArray, zaezyinArray);
}
If the size of the initial obj is zero, push the input value to obj.
firstAaddData function is :
function firstAddData(d_idx, d_firstDate, d_secondDate, chozyinArray, zaezyinArray)
{
obj.push
(
{
"d_idx" : d_idx,
"ri_firstDate" : d_firstDate,
"ri_secondDate" : d_secondDate,
"ri_chozyinTime" : chozyinArray,
"ri_zaezyinTime" : zaezyinArray
}
);
}
Second obj.length> = 1,
At this time, the conditions described above are set.
This is, Of the values of the first pushed obj,
d_firstDate, and d_secondDate are compared with the newly inputted d_firstDate and d_secondDate.
else if(obj.length >= 1)
{
var filterObj = obj.filter(function(cur)
{
return cur.ri_firstDate == d_firstDate && cur.ri_secondDate == d_secondDate;
})
if(filterObj.length > 0)
{
filterObj.forEach(function(cur, idx)
{
if(chozyintime != "" && chozyintime != null)
{
cur.ri_chozyinTime.push(chozyintime);
}
})
}
else
{
firstAddData(d_idx, d_firstDate, d_secondDate, chozyinArray, zaezyinArray);
}
}
As a result, I got the following output.
{ri_zaezyinTime=[1231,1421,2561], ri_firstDate=2017-12-15, ri_chozyinTime=[5212, 2314], ri_secondDate=2017-12-26, d_idx=1}
However, exception handling is not implemented for duplicate values.
When you add a new input value (chozyintime), Compared to the n elements in the array, I want to make the alert window pop up when there are duplicate values.
How should I write code to implement what I want to implement?
I need your feedback. Help.

Function not console logging when called by other function

I have 2 functions on a single .js file.
function notUsed(id) {
//default to false because if true then id not being used and good for new user
var notInUse = false;
console.log(notInUse);
return !notInUse;
}
function generateID() {
//number of zeros represents the number of digits in id code
const SIZEOFID = 10000000;
const ID_DIGITS = 7;
//letter to start id for non los rios people
const STRTOFID = "C";
//variable to hold finished id code & variable to hold 7 digit of id code
var id, idNum;
//loop to make sure id contains 7 digits and 1 letter and not used already
do {
idNum = Math.round(Math.random() * SIZEOFID);
idNum.toString();
id = (STRTOFID + idNum);
}while(id.length != (ID_DIGITS+1) && notUsed(id));
console.log(id);
}
When I call generateID() from my web page, the ID gets logged but false does not get logged(Obviously notUsed function is incomplete). However, if I call each function separately from my web page, both the ID and false get logged. How can I fix or work around this issue? Any comments help.
The logical and is short-circuiting because the first comparison is false. The second never gets evaluated, which is why it's not logging. It's not being called.
It`s happened because first condition in while id.length != (ID_DIGITS+1) return false, if first condition return false next conditions will not be called
Example:
function imreturnTrue() {
console.log('imreturnTrue');
return true
};
function impreturnFalse() {
console.log('impreturnFalse');
return false
};
function imreturnTrue1() {
console.log('imreturnTrue1');
return true
};
let example = imreturnTrue() && impreturnFalse() && imreturnTrue1();
// imreturnTrue impreturnFalse
let example1 = imreturnTrue() && imreturnTrue1() && impreturnFalse() ;
// imreturnTrue imreturnTrue1 impreturnFalse
let example2 = impreturnFalse() && imreturnTrue() && imreturnTrue1() ;
// impreturnFalse

how to check null in javaScript function?

I want to check null and empty id in JavaScript function,but if syntax isn't work ?
var id = "<%=Request["Id"]%>";
if (id !== "")
if (id !== null)
{var id = "<%=new Guid(Request["ID"].ToString())%>";
window.location = "/Controller/Action.aspx?Id=" + id; }
With javascript,
If you are trying to test for not-null (any value that is not explicitly NULL) this should work for you:
if( myVar !== null ) {
// your code
}
If you are only interested to test for not-empty (null value, zero number, empty string etc..) then try:
if( !myVar ) {
// your code
}
If you want to test for if a variable is defined at all (which I believe is what you are trying to achieve) then you can do it like:
if( typeof myVar !== 'undefined' ) {
// your code
}
Please let me know if it works for you.
Read into binary logic:
var id = "<%=Request["Id"]%>";
if (id !== "" && id != null) {
var id = "<%=new Guid(Request["ID"].ToString())%>";
window.location = "/Controller/Action.aspx?Id=" + id;
}
Then again, var id = "<%=Request["Id"]%>"; will never be null, only empty string, so perhaps you can drop that check altogether.

Javascript dynamic conditioning

I want to build a IF condition which is built dynamically based on the parameters it gets. More over, this is expected to be built as a plugin.
For instance, there are 3 parameters for student object, called age,name, phone_numbers. Also, there is a option object for selection parameters.
In the condition,
if(student.age >option.age & student.name == option.name & student.phonenumbers == option.phonenumbers ){
// do stuff
}
If any parameter is missing, it should not be included in the condition. For example, assume, in case option.name is undefined, then the if condition should be prepared as following,
if(student.age >option.age & student.phonenumbers == option.phonenumbers ){
// do stuff
}
Moreover, why this kind of thing is required is, here an array of (500 objects) students objects are iterated. The above condition can be splitted into seperat conditions, but then the iteration will be multipled by the number of conditions !!!. So I m looking for a way to add all conditions into one.
However, my approach is, create the expression as a string and then execute it with eval(..),but as far as I know that using eval can lead vulnerabilities.
Any one let me know a way to implement a dynamic conditions.
Note that the JavaScript and operator is &&.
For your example, this should work:
if((!student.age || student.age>option.age) &&
(!student.name || student.name==option.name) &&
(!student.phonenumbers || student.phonenumbers==option.phonenumbers)
) {
}
How about
function testStudent(student,option) {
var res = [];
var test = true;
if (student.age) res.push(student.age > option.age);
if (student.name) res.push(student.name == option.name);
if (student.phonenumbers) res.push(student.phonenumbers == option.phonenumbers);
for (var i=0;i<res.length;i++) {
test = test && res[i];
}
if (res.length > 0 && test) {
//do stuff
}
}
generic:
function testObjects(obj1,obj2) {
for (var o in obj1) { // assuming obj2 is a superset of obj1
if (o === "age" && obj1.age <= obj2.age) return false;
if (obj1.hasOwnProperty(o) && obj1[o] != obj2[o]) return false;
}
return true;
}
var ok = testObjects(student,option);
You can have your conditions in functions and those functions in an Array. so then you can do a loop in the Array and call every function (condition).
var aConds = [];
function firstCond(params) {return (params<0)};
function secondCond(params) {return(params!='hi')};
aConds.push(firstCond);
...
for(var i=0;i<aConds.length;i++)
{
if(!aConds[i](params)) console.log("a condition has not been meet");
}
Would it work to allow undefined in each condition?
if((student.age == undefined || student.age > option.age) && (student.name == undefined || student.name == option.name) ...

javascript not removing undefined objects from array

I've got an in page text search using JS, which is here:
$.fn.eoTextSearch = function(pat) {
var out = []
var textNodes = function(n) {
if (!window['Node']) {
window.Node = new Object();
Node.ELEMENT_NODE = 1;
Node.ATTRIBUTE_NODE = 2;
Node.TEXT_NODE = 3;
Node.CDATA_SECTION_NODE = 4;
Node.ENTITY_REFERENCE_NODE = 5;
Node.ENTITY_NODE = 6;
Node.PROCESSING_INSTRUCTION_NODE = 7;
Node.COMMENT_NODE = 8;
Node.DOCUMENT_NODE = 9;
Node.DOCUMENT_TYPE_NODE = 10;
Node.DOCUMENT_FRAGMENT_NODE = 11;
Node.NOTATION_NODE = 12;
}
if (n.nodeType == Node.TEXT_NODE) {
var t = typeof pat == 'string' ?
n.nodeValue.indexOf(pat) != -1 :
pat.test(n.nodeValue);
if (t) {
out.push(n.parentNode)
}
}
else {
$.each(n.childNodes, function(a, b) {
textNodes(b)
})
}
}
this.each(function() {
textNodes(this)
})
return out
};
And I've got the ability to hide columns and rows in a table. When I submit a search and get the highlighted results, there would be in this case, the array length of the text nodes found would be 6, but there would only be 3 highlighted on the page. When you output the array to the console you get this:
So you get the 3 tags which I was expecting, but you see that the array is actually consisting of a [span,undefined,span,undefined,undefined,span]. Thus giving me the length of 6.
<span>
<span>
<span>
[span, undefined, span, undefined, undefined, span]
I don't know why it's not stripping out all of the undefined text nodes when I do the check for them. Here's what I've got for the function.
performTextSearch = function(currentObj){
if($.trim(currentObj.val()).length > 0){
var n = $("body").eoTextSearch($.trim(currentObj.val())),
recordTitle = "matches",
arrayRecheck = new Array(),
genericElemArray = new Array()
if(n.length == 1){
recordTitle = "match"
}
//check to see if we need to do a recount on the array length.
//if it's more than 0, then they're doing a compare and we need to strip out all of the text nodes that don't have a visible parent.
if($(".rows:checked").length > 0){
$.each(n,function(i,currElem){
if($(currElem).length != 0 && typeof currElem != 'undefined'){
if($(currElem).closest("tr").is(":visible") || $(currElem).is(":visible")){
//remove the element from the array
console.log(currElem)
arrayRecheck[i] = currElem
}
}
})
}
if(arrayRecheck.length > 0){
genericElemArray.push(arrayRecheck)
console.log(arrayRecheck)
}
else{
genericElemArray.push(n)
}
genericElemArray = genericElemArray[0]
$("#recordCount").text(genericElemArray.length + " " +recordTitle)
$(".searchResults").show()
for(var i = 0; i < genericElemArray.length; ++i){
void($(genericElemArray[i]).addClass("yellowBkgd").addClass("highLighted"))
}
}
else{
$(".highLighted").css("background","none")
}
}
If you look at the code below "//check to see if we need to do a recount on the array length. ", you'll see where I'm stripping out the text nodes based off of the display and whether or not the object is defined. I'm checking the length instead of undefined because the typeof == undefined wasn't working at all for some reason. Apparently, things are still slipping by though.
Any idea why I'm still getting undefined objects in the array?
My apologies for such a big post!
Thanks in advance
I've modified your eoTextSearch() function to remove dependencies on global variables in exchange for closures:
$.fn.extend({
// helper function
// recurses into a DOM object and calls a custom function for every descendant
eachDescendant: function (callback) {
for (var i=0, j=this.length; i<j; i++) {
callback.call(this[i]);
$.fn.eachDescendant.call(this[i].childNodes, callback);
}
return this;
},
// your text search function, revised
eoTextSearch: function () {
var text = document.createTextNode("test").textContent
? "textContent" : "innerText";
// the "matches" function uses an out param instead of a return value
var matches = function (pat, outArray) {
var isRe = typeof pat.test == "function";
return function() {
if (this.nodeType != 3) return; // ...text nodes only
if (isRe && pat.test(this[text]) || this[text].indexOf(pat) > -1) {
outArray.push(this.parentNode);
}
}
};
// this is the function that will *actually* become eoTextSearch()
return function (stringOrPattern) {
var result = $(); // start with an empty jQuery object
this.eachDescendant( matches(stringOrPattern, result) );
return result;
}
}() // <- instant calling is important here
});
And then you can do something like this:
$("body").eoTextSearch("foo").filter(function () {
return $(this).closest("tr").is(":visible");
});
To remove unwanted elements from the search result. No "recounting the array length" necessary. Or you use each() directly and decide within what to do.
I cannot entirely get my head around your code, but the most likely issue is that you are removing items from the array, but not shrinking the array afterwards. Simply removing items will return you "undefined", and will not collapse the array.
I would suggest that you do one of the following:
Copy the array to a new array, but only copying those items that are not undefined
Only use those array items that are not undefined.
I hope this is something of a help.
Found the answer in another post.
Remove empty elements from an array in Javascript
Ended up using the answer's second option and it worked alright.

Categories

Resources