React JavaScript How to optimize this if / or statement - javascript

Do you have a better way to create this if / elseif sentence?
if ((navigator.userAgent.indexOf('Opera') || navigator.userAgent.indexOf('OPR')) != -1) {
this.state.isBrowserAllowed = true;
} else if (navigator.userAgent.indexOf('Chrome') != -1) {
this.state.isBrowserAllowed = true;
} else if (navigator.userAgent.indexOf('Safari') != -1) {
this.state.isBrowserAllowed = true;
} else if (navigator.userAgent.indexOf('Firefox') != -1) {
this.state.isBrowserAllowed = true;
}

I'd use a regular expression instead.
this.setState({
...this.state,
isBrowserAllowed: /Opera|OPR|Chrome|Safari|Firefox/.test(navigator.userAgent)
});
Also, as the comment notes, state should not be mutated in React - use setState instead.

Related

Verifying Referral URL String & Cookie String with Javascript IF

I am attempting to verify the referral URL and whether or not a cookie contains a certain string and then perform an action, however right now - my IF statement is always TRUE.
When I remove the ref1 section, and only keep getcookie, I believe the statement is false; although then my else if does not work
Nevertheless, I believe the construction of this If statement is missing something.
if (ref1.indexOf('ccov') || ref1.indexOf('top10') || ref1.indexOf('cenf') || ref1.indexOf('aip')||
ref1.indexOf('constructioncoverage')||
ref1.indexOf('aginginplace')|| ref1.indexOf('seniorliving')|| ref1.indexOf('seniorlist') ||
((getcookie('track-page-1').indexOf('ccov')>-1) > -1) ||
((getcookie('track-page-1').indexOf('top10')>-1) > -1) ||
((getcookie('track-page-1').indexOf('cenf')>-1) > -1) ||
((getcookie('track-page-1').indexOf('aip')>-1) > -1)) {
Complete Code if Interested:
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
var userLang = navigator.language || navigator.userLanguage;
s1.async=true;
var country = ('; '+document.cookie).split('; country=').pop().split(';')[0];
var ref1 = document.referrer;
// if (['BS'].indexOf(country) > -1){
// s1.src='https://embed.tawk.to/61488c2325797d7a89ffe3dc/1fg1m6qod';
// }
// else if (country == 'MX') {
// s1.src='https://embed.tawk.to/6148c99f25797d7a89ffef5b/1fg2576ci';
// }
if (ref1.indexOf('ccov') || ref1.indexOf('top10') || ref1.indexOf('cenf') || ref1.indexOf('aip') || ref1.indexOf('constructioncoverage') || ref1.indexOf('aginginplace') || ref1.indexOf('seniorliving') || ref1.indexOf('seniorlist') || ((getcookie('track-page-1').indexOf('ccov')>-1) > -1) || ((getcookie('track-page-1').indexOf('top10')>-1) > -1) || ((getcookie('track-page-1').indexOf('cenf')>-1) > -1) || ((getcookie('track-page-1').indexOf('aip')>-1) > -1)) {
s1.src='https://embed.tawk.to/620675459bd1f31184dc28c0/1frkjk5mj';
}
else if (userLang.match(/^es/)) {
s1.src='https://embed.tawk.to/609a845c185beb22b30c3bf3/1f5dpa29q';
}
else if (userLang.match(/^pt/)) {
s1.src='https://embed.tawk.to/609a845c185beb22b30c3bf3/1f63jmv3f';
}
else if (userLang.match(/^fr/)) {
s1.src='https://embed.tawk.to/609a845c185beb22b30c3bf3/1fa3s0cbv';
}
else if (userLang.match(/^ru/)) {
s1.src='https://embed.tawk.to/609a845c185beb22b30c3bf3/1fa3rv0no';
}
else if (userLang.match(/^lv/)) {
s1.src='https://embed.tawk.to/609a845c185beb22b30c3bf3/1fa3tcrog';
}
else if (userLang.match(/^et/)) {
s1.src='https://embed.tawk.to/609a845c185beb22b30c3bf3/1fa3tv7ll';
}
else if (userLang.match(/^lt/)) {
s1.src='https://embed.tawk.to/60e765f7649e0a0a5ccb3f41/1fa3uck2u';
}
else if (userLang.match(/^sv/)) {
s1.src='https://embed.tawk.to/60e765f7649e0a0a5ccb3f41/1fa5mfs8d';
}
else if (userLang.match(/^de/)) {
s1.src='https://embed.tawk.to/60e765f7649e0a0a5ccb3f41/1fa5muuvn';
}
else if (userLang.match(/^no/)) {
s1.src='https://embed.tawk.to/60e765f7649e0a0a5ccb3f41/1fa5ncduf';
}
else if (userLang.match(/^fi/)) {
s1.src='https://embed.tawk.to/60e765f7649e0a0a5ccb3f41/1fa5nudj7';
}
else if (userLang.match(/^nl/)) {
s1.src='https://embed.tawk.to/60e8531a649e0a0a5ccb61ee/1fa5o97t4';
}
else if (userLang.match(/^da/)) {
s1.src='https://embed.tawk.to/60e8531a649e0a0a5ccb61ee/1fa5orip4';
}
else if (userLang.match(/^el/)) {
s1.src='https://embed.tawk.to/60e8531a649e0a0a5ccb61ee/1fa5pkm1k';
}
else if (userLang.match(/^it/)) {
s1.src='https://embed.tawk.to/60e8531a649e0a0a5ccb61ee/1fa5q4uh2';
}
else if (userLang.match(/^pl/)) {
s1.src='https://embed.tawk.to/60e8531a649e0a0a5ccb61ee/1fa5qj4r7';
}
else if (userLang.match(/^cs/)) {
s1.src='https://embed.tawk.to/60e85defd6e7610a49aa78ec/1fa5qtrst';
}
else if (userLang.match(/^ro/)) {
s1.src='https://embed.tawk.to/60e85defd6e7610a49aa78ec/1fa5rl5gg';
}
else if (userLang.match(/^be/)) {
s1.src='https://embed.tawk.to/60e85defd6e7610a49aa78ec/1fa5rvbod';
}
else if (userLang.match(/^uk/)) {
s1.src='https://embed.tawk.to/60e85defd6e7610a49aa78ec/1fa5sgafc';
}
else if (userLang.match(/^hu/)) {
s1.src='https://embed.tawk.to/60e85defd6e7610a49aa78ec/1fa5t38bi';
}
else if (userLang.match(/^hr/)) {
s1.src='https://embed.tawk.to/60e8697ad6e7610a49aa7abc/1fa5to1mj';
}
else if (userLang.match(/^sr/)) {
s1.src='https://embed.tawk.to/60e8697ad6e7610a49aa7abc/1fa5u9emd';
}
else if (userLang.match(/^ka/)) {
s1.src='https://embed.tawk.to/60e8697ad6e7610a49aa7abc/1fa5uus6k';
}
else if (userLang.match(/^sk/)) {
s1.src='https://embed.tawk.to/60e8697ad6e7610a49aa7abc/1fa5vdsc3';
}
else if (userLang.match(/^tr/)) {
s1.src='https://embed.tawk.to/60e8697ad6e7610a49aa7abc/1fa60012u';
}
else if (userLang.match(/^ar/)) {
s1.src='https://embed.tawk.to/60e8697ad6e7610a49aa7abc/1fa60cgb7';
}
else {
s1.src='https://embed.tawk.to/60a7b623b1d5182476bb3457/1f67huun6';
}
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
It's tricky to debug this code as a sample of the value of ref1 is not provided. However, I can give some advice on where to go with this.
The indexOf method returns either the index of the substring/element provided, or -1 if not present. Be aware that Boolean(-1) returns true.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
document.referrer is a string, so you should probably make use of the includes method on string. This properly yields true when the substring is present, and false when it is not.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
Try replacing the indexOf methods on ref1 with includes like so:
if (ref1.includes('ccov') || ref1.includes('top10') || ref1.includes('cenf') || ref1.includes('aip') ||
ref1.includes('constructioncoverage') ||
ref1.includes('aginginplace') || ref1.includes('seniorliving') || ref1.includes('seniorlist') ||
((getcookie('track-page-1').indexOf('ccov') > -1) > -1) ||
((getcookie('track-page-1').indexOf('top10') > -1) > -1) ||
((getcookie('track-page-1').indexOf('cenf') > -1) > -1) ||
((getcookie('track-page-1').indexOf('aip') > -1) > -1)) {
}

Comma separated expression simplify

I'm trying to simplify code below
if (a ||
node != r._start ||
(start = n + r._startOff, a = true),
a && node == r._end) { .... }
Can someone help me to separate this if condition to simplify form? (without commas)?
The code in the if condition will always run... this is the simplify version:
var doYourStuff = false;
if (a || node != r._start) {
doYourStuff = true;
} else {
start = n + r._startOff;
a = true;
if (node == r._end) {
doYourStuff = true;
}
}
if (doYourStuff) {
// ... do your stuff
}

How to turn ternary if statement back into standard javascript?

I'm working with this ternary if statement:
a[textProp] = _newText + ' (' + (_newText === a[textProp] ? 'no change' : 'changed') + ')';
And I'd like to turn it back into standard javascript (for the sake of readability). I additionally want to make it into an if, else if, else statement to test if the variable is empty/null.
This is what I have, which doesn't work:
if (_newText = null) {
'Invalid Record';
}
else if (_newText === a[textProp]) {
'no change';
}
else(_newText != a[textProp]) {
'changed';
}
+ ')';
if (_newText = null) {
^
needs to be
if (_newText == null) {
^^
or
if (_newText === null) {
^^^
And you need to build up your string
a[textProp] = 'Invalid Record';
For the sake of readability, I'd start with something like this, where each state is checked explicitly (valid and changed):
var isValid = true;
if (_newText == null || _newText.trim().length === 0) {
isValid = false;
}
var hasChanged = false;
if (isValid && _newText !== a[textProp]) {
hasChanged = true;
}
if (!isValid) {
a[textProp] = 'Invalid Record';
}
else if (hasChanged) {
a[textProp] = _newText + ' (changed)';
}
else {
a[textProp] += ' (no change)';
}
But, I also think it's not right to store the result of the tests as a string inside a[textProp], it could invalidate future tests. I'd probably have separate keys for the test results (as a flag), e.g.: a.valid[textProp] and a.changed[textProp] (in this case, textProp can never be "valid" or "changed"). Even better would be to store the text in a[textProp].text, and the flags in a[textProp].valid and a[textProp].changed.

jQuery not returning any value

I have some code that checks if the contents of the form is valid. checkEmpty, checkNumeric and checkEmail is working fine if i comment out the checkFile function. But if I include checkFile, it breaks the code causing the function not to return any value.
Here is the checkFile function. It's supposed to check the file extension.
$.fn.checkFile = function(fileValue) {
//var fileName = contactform.cv.value;
var extension = fileValue.substring(fileValue.lastIndexOf('.') + 1);
alert(extension);
if(extension === 'jpg' || extension === 'jpeg' ||extension === 'docx' ||extension === 'pdf' ||extension === 'xlsx'){
alert("correct extension");
return true;
}else{
alert("incorrect extension");
return false;
}
};
Also the function should be working fine. I tried it seperately to see if it gets the extension properly.
Here is the whole code in case its needed
$(window).load(function() {
// validations
$.fn.checkEmpty = function(emp) {
if(emp === ""){
alert("field is empty");
return false;
}else{
alert("not empty");
return true;
}
};
$.fn.checkEmail = function(email) {
var regex = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
if(regex.test(email)){
alert("mail is valid");
return true;
} else {
alert("mail is invalid");
return false;
}
};
$.fn.checkNumeric = function(value) {
// 10 digits for phone number ?
/*
if (value.length !== 10 || value === "" || !$.isNumeric(value)) {
alert("not a numerical value");
} else {
alert("numerical value");
}*/
var regex =new RegExp(/^(?:\d*\,\d*|\d+)$/);
if(regex.test(value) && value!==""){
alert("numerical value");
return true;
} else {
alert("not numerical value");
return false;
}
};
$.fn.checkFile = function(fileValue) {
//var fileName = contactform.cv.value;
var extension = fileValue.substring(fileValue.lastIndexOf('.') + 1);
alert(extension);
if(extension === 'jpg' || extension === 'jpeg' ||extension === 'docx' ||extension === 'pdf' ||extension === 'xlsx'){
alert("correct extension");
return true;
}else{
alert("incorrect extension");
return false;
}
};
$.fn.checkField = function() {
var empty = "empty";
var numeric = "numeric";
var email = "email";
var file = "file";
var flag=0;
var retval;
$("input:text").each(function() {
var required = $(this).data("reqs");
if(required.toLowerCase().indexOf(empty) !== -1){
retval = $(this).checkEmpty($(this).val());
if(retval === false){
flag++;
$(this).after('<span style="color:red">*</span>');
}
}
if (required.toLowerCase().indexOf(numeric) !== -1){
retval = $(this).checkNumeric($(this).val());
if(retval === false){
flag++;
$(this).after('<span style="color:red">*</span>');
}
}
if(required.toLowerCase().indexOf(email) !== -1){
retval = $(this).checkEmail($(this).val());
if(retval === false){
flag++;
$(this).after('<span style="color:red">*</span>');
}
}
});
$("input:file").each(function() {
if(required.toLowerCase().indexOf(file) !== -1){
retval = $(this).checkFile($(this).val());
if(retval === false){
flag++;
$(this).after('<span style="color:red">*</span>');
}
}
});
alert(flag);
return (flag > 0) ? false : true;
};
});
Thanks for any help.
As Bergi pointed it out, it doesn't make much sense to add the function to the prototype if you pass it the filename as a parameter...
However, adding it to the prototype can be a good idea if you actually use this within the method:
$.fn.checkFile = function(){
var filename = $(this).val();
if (/(?:jpe?g|docx|pdf|xlsx)$/.test(filename)){
return true;
}else{
return false;
}
};
You can test this method at http://jsfiddle.net/NVvzN/. Try choosing different files from your computer to see how it works.
PS: my guess is, if you accept .docx and .xlsx, you should also accept .doc and .xls; in that case, the regular expression would be /(?:jpe?g|docx?|pdf|xlsx?)$/

SlickGrid- Need of insensitive case filter

Is there's a way to change the filter from sensitive case to insensitive?
Thank you.
Here’s the relevant section of a working example using the DataView filter. Notice the searchString variable is converted to lowercase when the value is first defined and then it's compared to lowercase strings within the myFilter function.
function myFilter(item, args) {
if (args.searchString != "" && item["FirstName"].toLowerCase().indexOf(args.searchString) == -1 && item["LastName"].toLowerCase().indexOf(args.searchString) == -1) {
return false;
}
return true;
}
....
$("#txtSearch").keyup(function (e) {
Slick.GlobalEditorLock.cancelCurrentEdit();
// clear on Esc
if (e.which == 27) {
this.value = "";
}
searchString = this.value.toLowerCase();
updateFilter();
});
function updateFilter() {
dataView.setFilterArgs({
searchString: searchString
});
dataView.refresh();
}
// initialize the model after all the events have been hooked up
dataView.beginUpdate();
dataView.setItems(data);
dataView.setFilterArgs({
searchString: searchString
});
dataView.setFilter(myFilter);
dataView.endUpdate();
Guessing you are talking about the DataView filter, the implementation of the filter functionality is totally up to you. Note the filter function used in the SlickGrid examples - that function is set as the filter using dataView.setFilter(your_function_here). So implement the filter function as you want and set it to the dataView
function filter(item) {
// String Should Match Each Other
/* for (var columnId in columnFilters) {
if (columnId !== undefined && columnFilters[columnId] !== "") {
var c = grid.getColumns()[grid.getColumnIndex(columnId)];
if (item[c.field] != columnFilters[columnId]) {
return false;
}
}
} */
for (var columnId in columnFilters) {
if (columnId !== undefined && columnFilters[columnId] !== "") {
var c = grid.getColumns()[grid.getColumnIndex(columnId)];
// This Case Sensitive
//if (!(item[c.field] && (""+item[c.field]).indexOf(columnFilters[columnId]) !== -1)) {
if (!(item[c.field] && (""+item[c.field].toLowerCase()).indexOf(columnFilters[columnId].toLowerCase()) !== -1)) {
// Case in-Sensitive
return false;
}
}
}
return true;
}

Categories

Resources