How to make a maintainable list of conditions - javascript

I have this code, which in time could be hard to read and maintain - numbers could come and go. How do I make this into an easy accessible maintainable list of conditions? Should I use an Array or something else?
var cs = 123456; //Some integer
if (cs >= 320000
&& cs <= 320026
|| cs == 320141
|| cs == 320143
|| cs == 320145
|| cs == 320147
|| cs == 320149
|| cs == 320151) {
new = 'Y';
} else if (cs >= 320100
&& cs <= 320112
|| cs >= 320114
&& cs <= 320116
|| cs >= 320123
&& cs <= 320128
|| cs == 320142
|| cs == 320144
|| cs == 320146
|| cs == 320148
|| cs == 320150
|| cs == 320152) {
new = 'N';
} else {
new = 'Unknown';
};

Yes, what you need is a array and an indexOf method.
Example:
if (cs >= 320000 && cs <= 320026 || $.inArray(value, valuesarray) > -1) {
--
}
https://stackoverflow.com/questions/16910305/if-or-shorter-way/16910313#16910313

Related

Check values in a form (Javascript)

I've five variables in a form, for simplicity I named them A, B, C, D and E.
In order to submit the form (A or (B or C)) and (D or E) must have a value (I hope it's clear :P).
I've tried with
if ((A == "" || (B == "" || C == "")) && (D == "" || E == "")) {
alert ("Error!");
} else {
form.submit();
}
But it doesn't work in every case. For example, if A, B and C have a value, the form is submitted even if neither D or E have values.
Thank you for the help!
If you have all strings, you could just reverse the condition and check all with logical AND and one OR.
var a = '', b = '', c = '', d = '', e = '';
if (a && b && c || d && e) {
console.log('form.submit();');
} else {
console.log('Error!');
}
Why it works:
given
(A == "" || (B == "" || C == "")) && (D == "" || E == "")
simplified A == "" is equivalent to !A
(A == "" || B == "" || C == "") && (D == "" || E == "")
(!A || !B || !C) && (!D || !E)
De Morgan's laws !(a && b) = !a || !b or !(a || b) = !a && !b
(!A || !B || !C) && (!D || !E)
!(A && B && C) && !(D && E)
!((A && B && C) || (D && E))
operator precedence
!(A && B && C || D && E)
now switch/negate then <-> else
A && B && C || D && E
if (A == "" || B == "" || C == "" && (D == "" || E == "")) {
alert ("Error!");
} else {
form.submit();
}
You need to change your logic to:
if ((A != "" || (B != "" || C != ""))
&& (D != "" || E != "")) {
form.submit();
} else {
alert ("Error!");
}
The alternative is to do it like so:
if ((A == "" && (B == "" && C == ""))
|| (D == "" && E == "")) {
alert ("Error!");
} else {
form.submit();
}
Edit: the first snippet can be refactored to the following:
if ((A || (B || C )) && (D || E )) {
form.submit();
} else {
alert ("Error!");
}
And the same can be done with the second snippet with the NOT operator !.
I updated the code a bit. I think this should work for you.
function isNonEmpty(string) {
//returning the string's truthiness value
return string.trim() ? true : false;
}
//change these values around to make sure the logic is correct
var A = "cat",
B = " ",
C = "dog",
D = "",
E = " turtle";
//almost exactly what you have just calling a function for neatness
if ((isNonEmpty(A) || isNonEmpty(B) || isNonEmpty(C)) &&
(isNonEmpty(D) || isNonEmpty(E))) {
console.log("Valid form. Time to submit!");
} else {
console.log("Invalid form. Please check your values!");
}

Why use (!fn || zid(handler.fn) === zid(fn)) to (!fn || handler.fn === fn) in zepto.js - event.js?

In event.js, to judge the same handler, here is code:
return handler
&& (!event.e || handler.e == event.e)
&& (!event.ns || matcher.test(handler.ns))
&& (!fn || zid(handler.fn) === zid(fn))
&& (!selector || handler.sel == selector)
Why use (!fn || zid(handler.fn) === zid(fn)) to (!fn || handler.fn === fn)
Here is the source code of zid
var _zid = 1
function zid(element) {
return element._zid || (element._zid = _zid++)
}
if I have to judge two functions, a === b is enough
why to use zid(a) === zid(b)? Maybe some trap?
I don't know why?
Here is the source code of zepto.js event.js: https://github.com/madrobby/zepto/blob/master/src/event.js

missing ) after argument list when creating a variable right after a for statement

I am trying to create the Bagel game and keep getting missing ) after argument list when I try to create the guess variable right after the for statement. Can someone tell me how to fix this?
alert('Lets play the bagel game! If you can guess my three digit number (with each digit being unique) within 20 turns, then you win! I will only provide you with three hints. Pico, which means one digit is correct, but in the wrong position. Fermi, which means one digit is correct and in the right position. Bagels, which means no digits are correct');
//computer generates number
function numberRange(){
var number = Math.round(Math.random()*1000);
var num =number.toString();
if (number <= 100 || number == 1000){
numberRange();
}
else if (num[0] == num[1] || num[0] == num[2] || num[1]==num[2]){
numberRange();
}
else if (number == undefined || num == undefined){
numberRange();
}else{
var numSave = JSON.stringify(num);
sessionStorage.setItem('number',numSave);
}}
numberRange();
var numGet = sessionStorage.getItem('number');
var numUse = JSON.parse(numGet);
//game start
for (i=1;i<21;i++){
var validNumber = /\d{3}/;
var guess = prompt('Turn ' + i ': Guess a number!');
while (validNumber.test(guess) == false) {
alert('Put in a three digit number!');
var guess = prompt('Turn ' + i ': Guess a number!');
}
if (validNumber.test(guess)){
var guessNum = guess.toString();
if (guessNum[0] == numUse[0] && guessNum[1] && numUse[1] && guessNum[2] == numUse[2]){
alert('Congratulations! You win!');
break
}
else if ((guessNum[0] == numUse[0] || guessNum[1] == numUse[1] || guessNum[2] == numUse[2]) && (guessNum[0] == numUse[1] || guessNum[0] == numUse[2] || guessNum[1] == numUse[0] || guessNum[1] == numUse[2] || guessNum[2] == numUse[0] || guessNum[2] == numUse[3])){
alert('Pico and Fermi!');
}else if(guessNum[0] == numUse[1] || guessNum[0] == numUse[2] || guessNum[1] == numUse[0] || guessNum[1] == numUse[2] || guessNum[2] == numUse[0] || guessNum[2] == numUse[3]){
alert('Pico!');
}else if (guessNum[0] == numUse[0] || guessNum[1] == numUse[1] || guessNum[2] == numUse[2]){
alert('Fermi!');
}else (guessNum[0] != numUse[0] && guessNum[0] != numUse[1] && guessNum[0] != numUse[2] && guessNum[1] != numUse[0] && guessNum[1] != numUse[1] && guessNum[1] != numUse[2] && guessNum[2] != numUse[0] && guessNum[2] != numUse[1] && guessNum[2] != numUse[2]){
alert('Begels!');
}
}
}
I see several issues.
var guess = prompt('Turn ' + i ': Guess a number!');
is missing + after i '
It should be like this:
var guess = prompt('Turn ' + i + ': Guess a number!');
You're also defining the same variable name twice inside the for scope, just do guess = prompt('Turn ' + i ': Guess a number!'); inside the while loop.
I didn't check the rest of the code, but this should get you started.
you seem to have missed a "+" as a part of string concatenation.
prompt('Turn ' + i+': Guess a number!');
instead of
prompt('Turn ' + i': Guess a number!');
What the other folks said (there are 2 places you need + signs, l#s 25, 28) and your final else needs an if before the test clause (L# 41). After that it should at least run. A few other comments:
only var a variable the first time it is declared.
look into switch statements and use them when you have more than 2 options and a default.
try to break up long lines (as in add line feeds) and keep all the code on the screen. Javascript doesn't care at all about white space so use it. Far easier to debug things when you can see it all.
a good editor will find this stuff for you. There are a lot of free ones (Atom, Komodo) that do a decent job of syntax highlighting and error detection.

Internet Explorer may run slowly: change of logic to be done

TableHandler.prototype.IsAlreadySelected = function(dataToCheck)
{
var _this = this;
if (_this.NewTemplateUsageSelected.length > 0)
{
var len = _this.NewTemplateUsageSelected.length;
for (var i = 0; i < len; i++)
{
var an = _this.NewTemplateUsageSelected[i];
var isTemplateUsageDataDuplicate=false;
var isNonApplicableCGDataDuplicate=false;
if ((an.CustomerName == dataToCheck.CustomerName) &&
(an.ProgramName == dataToCheck.ProgramName) &&
(an.WorkpackageName == dataToCheck.WorkpackageName) &&
(an.ActivityName == dataToCheck.ActivityName) &&
(an.SelectedWorkFlowType == dataToCheck.SelectedWorkFlowType) &&
(an.SelectedWorkFlowCategory == dataToCheck.SelectedWorkFlowCategory) &&
(an.ReWorkflow== dataToCheck.ReWorkflow) &&
(an.AllowCheckGroupSelection == dataToCheck.AllowCheckGroupSelection) &&
(an.InitiatorGroupSelection == dataToCheck.InitiatorGroupSelection) &&
(an.R1GroupSelection == dataToCheck.R1GroupSelection) &&
(an.R2GroupSelection == dataToCheck.R2GroupSelection) &&
(an.R3GroupSelection == dataToCheck.R3GroupSelection) &&
(an.R4GroupSelection == dataToCheck.R4GroupSelection) &&
(an.InitiatorMinReworkEffort == dataToCheck.InitiatorMinReworkEffort) &&
(an.R1MinReworkEffort == dataToCheck.R1MinReworkEffort) &&
(an.R2MinReworkEffort == dataToCheck.R2MinReworkEffort) &&
(an.R3MinReworkEffort == dataToCheck.R3MinReworkEffort) &&
(an.R4MinReworkEffort == dataToCheck.R4MinReworkEffort) &&
(an.AllowFileAttachment == dataToCheck.AllowFileAttachment) &&
(an.QualityReviewer== dataToCheck.QualityReviewer) &&
(an.AllowLiabiltySelection == dataToCheck.AllowLiabiltySelection)&&
(an.SetToInactive == dataToCheck.SetToInactive)&&
(an.NonApplicabilityCheckGroupAllowed == dataToCheck.NonApplicabilityCheckGroupAllowed))
{
istemplateusagedataduplicate=true;
}
var checkgroupslendataToCheck=dataToCheck.NonApplicableCheckGroupList.length;
var nalen=an.NonApplicableCheckGroupList.length;
if(checkgroupslendataToCheck == nalen )
{
for (var i = 0 ;i < checkgroupslendataToCheck ; i++)
{
var naDatatocheck= dataToCheck.NonApplicableCheckGroupList[i];
var naData=an.NonApplicableCheckGroupList[i];
if(
( naDatatocheck.INonApplicability == naData.INonApplicability )&&
( naDatatocheck.R1NonApplicability == naData.R1NonApplicability )&&
( naDatatocheck.R2NonApplicability == naData.R2NonApplicability) &&
( naDatatocheck.R3NonApplicability == naData.R3NonApplicability )&&
( naDatatocheck.R4NonApplicability == naData.R4NonApplicability))
isNonApplicableCGDataDuplicate=true;
else
{
isNonApplicableCGDataDuplicate=false;
break;
}
}
if(isNonApplicableCGDataDuplicate==true && istemplateusagedataduplicate==true)
return true;
}
}
}
};
The above code is causing error Internet may run slowly. When i seached for a solution i got solutions like change of registry and IE version, Move the code to cdebehind,usage of plugin etc.. Which are not feasible in our project. So I have to change the above logic.Any inbuilt function in javascript or jquery which i can use to campare a two nested list.
The inner loop needs to use a different variable as its counter or it will make the outer loop go on infinitely. Currently you are using i for both loops.

Looping through javascript function

I'm trying to loop my if statements inside a while loop through my function. But it will only hit the first if statement and stop looping.
Sample:
while(No.length == 0 || Name.length == 0 || Tel.length == 0
|| Date.length == 0 || Email.length == 0) {
alert("Don't leave blank!");
if (No.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
return false;
}
if(Name.length == 0) {
document.getElementById('Name').style.visibility = 'visible';
return false;
}
//continues same if statement for rest of the elements variables.
}
It will only go to the first if statement and will not loop through it.
You are returning from inside the loop; that breaks the loop. If you want to continue on to the next round of the loop, use continue instead. If you want to break out of the loop, but not return from the entire function, use break.
Now if you are using a jQuery loop, because it's really just a function, you do use return:
$.each([1,2,3,4], function(index, x) {
if (x < 4) return true; // equivalent to continue
if (x == 4) return false; // equivalent to break
});
but that's only for jQuery loops, not Javascript standard ones.
The first error I can see is you should escape your alert with '\' for example :
alert('Don\'t leave blank!');
And the loop with just continue if you write this :
while(No.length == 0 || Name.length == 0 || Tel.length == 0 || Date.length == 0 || Email.length == 0) {
if (No.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
}
if(Name.length == 0) {
document.getElementById('Name').style.visibility = 'visible';
}
return true;
}
Could also try:
while(No.length == 0 && Name.length == 0 && Tel.length == 0 && Date.length == 0 && Email.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
document.getElementById('Name').style.visibility = 'visible';
continue;
}
Maybe this?
function test_all_fields() {
var No = document.getElementById('No');
var Nos = document.getElementById('Nos');
var Name = document.getElementById('Name');
// ...
Nos.style.visibility = (No.value.length==0) ? 'visible':'hidden';
Names.style.visibility = (Name.value.length==0) ? 'visible':'hidden';
//...
//continues same if statement for rest of the elements variables.
if (No.value.length >0 && Name.value.length >0 && Tel.value.length>0 && Date.value.length >0 && Email.value.length>0) {
return true;
}
else {
alert("Don\'t leave blank!");
return false;
}
}

Categories