How can we reduce if else condition in javascript? - javascript
I am working on node js and mysql here i am using profile incomplete or complete logic so i have to check all the fields or empty or not so i have 28 fields i have used 28 if else can we make shorter code.
Here my code
so how we can reduce my code if we can reduce our code please share your solution.
Here no error this code is correct But I need to make shorter code it will be good.
let points = 0;
let point1 = 0;
let point2 = 0;
let point3 = 0;
let point4 = 0;
let point5 = 0;
let point6 = 0;
let point7 = 0;
let point8 = 0;
let point9 = 0;
let point10 = 0;
let point11 = 0;
let point12 = 0;
let point13 = 0;
let point14 = 0;
let point15 = 0;
let point16 = 0;
let point17 = 0;
let point18 = 0;
let point19 = 0;
let point20 = 0;
let point21 = 0;
let point22 = 0;
let point23 = 0;
let point24 = 0;
let point25 = 0;
let point26 = 0;
if (profileRes[0].username == null || profileRes[0].username == "") {
point1 = points + 10;
} else if (profileRes[0].username != null || profileRes[0].username != "") {
point1 = points += 0;
}
if (profileRes[0].phone == null || profileRes[0].phone == "") {
point2 = points + 10;
} else if (profileRes[0].phone != null || profileRes[0].phone != "") {
point2 = points += 0;
}
if (profileRes[0].email == null || profileRes[0].email == "") {
point3 = points + 10;
} else if (profileRes[0].email != null || profileRes[0].email != "") {
point3 = points += 0;
}
if (profileRes[0].company_name == null || profileRes[0].company_name == "") {
point4 = points + 10;
} else if (profileRes[0].company_name != null || profileRes[0].company_name != "") {
point4 = points += 0;
}
if (profileRes[0].profile_description == null || profileRes[0].profile_description == "") {
point5 = points + 10;
} else if (profileRes[0].profile_description != null || profileRes[0].profile_description != "") {
point5 = points += 0;
}
if (profileRes[0].short_description == null || profileRes[0].short_description == "") {
point6 = points + 10;
} else if (profileRes[0].short_description != null || profileRes[0].short_description != "") {
point6 = points += 0;
}
if (profileRes[0].company_url == null || profileRes[0].company_url == "") {
point7 = points + 10;
} else if (profileRes[0].company_url != null || profileRes[0].company_url != "") {
point7 = points += 0;
}
if (profileRes[0].company_linkedin == null || profileRes[0].company_linkedin == "") {
point8 = points + 10;
} else if (profileRes[0].company_linkedin != null || profileRes[0].company_linkedin != "") {
point8 = points += 0;
}
if (profileRes[0].company_instagram == null || profileRes[0].company_instagram == "") {
point9 = points + 10;
} else if (profileRes[0].company_instagram != null || profileRes[0].company_instagram != "") {
point9 = points += 0;
}
if (profileRes[0].company_facebook == null || profileRes[0].company_facebook == "") {
point10 = points + 10;
} else if (profileRes[0].company_facebook != null || profileRes[0].company_facebook != "") {
point10 = points += 0;
}
if (profileRes[0].number_of_employees == null || profileRes[0].number_of_employees == "") {
point11 = points + 10;
} else if (profileRes[0].number_of_employees != null || profileRes[0].number_of_employees != "") {
point11 = points += 0;
}
if (profileRes[0].company_logo == null || profileRes[0].company_logo == "") {
point12 = points + 10;
} else if (profileRes[0].company_logo != null || profileRes[0].company_logo != "") {
point12 = points += 0;
}
if (profileRes[0].founding_year == null || profileRes[0].founding_year == "") {
point13 = points + 10;
} else if (profileRes[0].founding_year != null || profileRes[0].founding_year != "") {
point13 = points += 0;
}
if (profileRes[0].is_profile_published == null || profileRes[0].is_profile_published == "") {
point14 = points + 10;
} else if (profileRes[0].is_profile_published != null || profileRes[0].is_profile_published != "") {
point14 = points += 0;
}
if (profileRes[0].legal_name == null || profileRes[0].legal_name == "") {
point15 = points + 10;
} else if (profileRes[0].legal_name != null || profileRes[0].legal_name != "") {
point15 = points += 0;
}
if (profileRes[0].billing_address == null || profileRes[0].billing_address == "") {
point16 = points + 10;
} else if (profileRes[0].billing_address != null || profileRes[0].billing_address != "") {
point16 = points += 0;
}
if (profileRes[0].zip_code == null || profileRes[0].zip_code == "") {
point17 = points + 10;
} else if (profileRes[0].zip_code != null || profileRes[0].zip_code != "") {
point17 = points += 0;
}
if (profileRes[0].vat_number == null || profileRes[0].vat_number == "") {
point18 = points + 10;
} else if (profileRes[0].vat_number != null || profileRes[0].vat_number != "") {
point18 = points += 0;
}
if (profileRes[0].sdi_codex == null || profileRes[0].sdi_codex == "") {
point19 = points + 10;
} else if (profileRes[0].sdi_codex != null || profileRes[0].sdi_codex != "") {
point19 = points += 0;
}
if (profileRes[0].benefits == null || profileRes[0].benefits == "") {
point20 = points + 10;
} else if (profileRes[0].benefits != null || profileRes[0].benefits != "") {
point20 = points += 0;
}
if (profileRes[0].category == null || profileRes[0].category == "") {
point21 = points + 10;
} else if (profileRes[0].category != null || profileRes[0].category != "") {
point21 = points += 0;
}
if (profileRes[0].branch == null || profileRes[0].branch == "") {
point22 = points + 10;
} else if (profileRes[0].branch != null || profileRes[0].branch != "") {
point22 = points += 0;
}
if (profileRes[0].coreActivities == null || profileRes[0].coreActivities == "") {
point23 = points + 10;
} else if (profileRes[0].coreActivities != null || profileRes[0].coreActivities != "") {
point23 = points += 0;
}
if (profileRes[0].districts == null || profileRes[0].districts == "") {
point24 = points + 10;
} else if (profileRes[0].districts != null || profileRes[0].districts != "") {
point24 = points += 0;
}
if (profileRes[0].legalFormCompany == null || profileRes[0].legalFormCompany == "") {
point25 = points + 10;
} else if (profileRes[0].legalFormCompany != null || profileRes[0].legalFormCompany != "") {
point25 = points += 0;
}
if (profileRes[0].commune == null || profileRes[0].commune == "") {
point26 = points + 10;
} else if (profileRes[0].commune != null || profileRes[0].commune != "") {
point26 = points += 0;
}
else {
}
let pint = point1 + point2 + point3 + point4 + point5 + point6 + point7 + point8 + point9 + point10 +point11 + point12 + point13 + point14 + point15 + point16 + point17 + point18 + point19 + point20 + point21 + point22 + point23 + point24 + point25 + point26;
let percentage = (pint * 100) / 260;
Should all keys in the profileRes[0] have a corresponding points variable? If yes, then something like this might work. This solution will put all of your points into one object instead of a list of variables:
const pointsMap = Object.entries(profileRes[0]).reduce((acc, [key, value]) => {
acc[key] = !!value ? 0 : 10
return acc
}, {})
// returns an object that has key/value pairs accessible by the profileRes[0] keys
// for example, {username: 10, email: 0, phone: 10...}
Note, the above answer uses !!value to determine if the value is truthy. This means values like null and "" will fail. undefined will also fail this check. If a key in profileRes[0] can be undefined and undefined should be considered a valid value, the line can change to be the following instead:
acc[key] = (value === null || value === "") ? 10 : 0
You can remove all the points variables
let points = 0;
for (let key in profileRes[0]) {
if (profileRes[0][key] === null || profileRes[0][key] === '') {
points += 10;
} else {
points += 0;
}
}
let percentage = (points * 100) / 260;
Related
why is this JavaScript slowing down my web page
I am new to JavaScript and i have written a function that refreshes nodes on a web age every 5 seconds. I load a json file of 68 bytes in size and parses the html changing data. After about 20 second the age freezes and slowing down the browser, also the class changes are not happening. I don't know if i have a memory leak or if i should just get the server to send the data. setInterval(function() { $.getJSON("/Assets/inplay.json", function(data){ var j_data = JSON.parse(data); var Curr = []; $.each(j_data, function(key, value){ Curr.push(value._id.$oid); chk = document.getElementById('HT-'+value._id.$oid); if (chk == null){ $('#in-play').append(addRow(value)); } else { var prefixes = ['GT-', 'HG-', 'HDA-', 'HA-', 'HP-', 'HOT-', 'HOffT-', 'HPI-', 'Fav-', 'AG-', 'ADA-', 'AA-', 'AP-', 'AOT-', 'AOffT-', 'API-', 'HMO-', '025-', '035-', '045-', 'AMO-', 'U25-', 'U35-', 'U45-', 'DMO-']; var values = [value.Stats[0].gt, value.Stats[0].hg, chkVal(value.Stats[0],'Dangerous_Attacks', 0), chkVal(value.Stats[0], 'Attacks', 0), chkVal(value.Stats[0], 'Possession', 0), chkVal(value.Stats[0], 'On_Target', 0), chkVal(value.Stats[0], 'Off_Target', 0), chkVal2(value.HomePI, 'PI'), chkVal3(value.Fav), value.Stats[0].ag, chkVal(value.Stats[0], 'Dangerous_Attacks', 1), chkVal(value.Stats[0], 'Attacks', 1), chkVal(value.Stats[0], 'Possession', 1), chkVal(value.Stats[0], 'On_Target', 1), chkVal(value.Stats[0], 'Off_Target', 1), chkVal2(value.AwayPI, 'PI'), marketsFunc(value, "MATCH_ODDS", 0), marketsFunc(value, "OVER_UNDER_25", 1), marketsFunc(value, "OVER_UNDER_35", 1), marketsFunc(value, "OVER_UNDER_45", 1), marketsFunc(value, "MATCH_ODDS", 1), marketsFunc(value, "OVER_UNDER_25", 0), marketsFunc(value, "OVER_UNDER_35", 0), marketsFunc(value, "OVER_UNDER_45", 0), marketsFunc(value, "MATCH_ODDS", 2)]; for (var i = 0, len = prefixes.length; i < len; i++) { if (values[i] != null && document.getElementById(prefixes[i]+value._id.$oid) != null) { //console.log(prefixes[i]+value._id.$oid); //console.log(values[i]); if (prefixes[i] == 'GT-' && value.Tactics != null){ if(value.Tactics.indexOf("HT-LTD") != -1 && values[i] == '45:00') { class_n = document.getElementById('HT-'+value._id.$oid).classList; class_n.add('HT-LTD'); class_n = document.getElementById('AT-'+value._id.$oid).classList; class_n.add('HT-LTD'); } else if (classArr.indexOf("HT-LTD") != -1 && values[i] != '45:00') { class_n = document.getElementById('HT-'+value._id.$oid).classList; class_n.remove('HT-LTD'); class_n = document.getElementById('AT-'+value._id.$oid).classList; class_n.remove('HT-LTD'); } } if (prefixes[i] == 'HPI-' && values[i] > 6) { class_n = document.getElementById('HT-'+value._id.$oid).classList; class_n.add('HI-PRESSURE'); } if (prefixes[i] == 'API-' && values[i] > 6) { //console.log('bob'); class_n = document.getElementById('AT-'+value._id.$oid).classList; class_n.add('HI-PRESSURE'); } if (prefixes[i] == 'HG-' && values[i] != document.getElementById(prefixes[i]+value._id.$oid).innerHTML) { document.getElementById('HG-'+value._id.$oid).className = 'GOAL'; } if (prefixes[i] == 'AG-' && values[i] != document.getElementById(prefixes[i]+value._id.$oid).innerHTML) { document.getElementById('AG-'+value._id.$oid).className = 'GOAL'; } if (prefixes[i] == 'HG-' && document.getElementById('HG-'+value._id.$oid).className == 'GOAL') { document.getElementById('HG-'+value._id.$oid).className = 'OLD-GOAL'; } if (prefixes[i] == 'AG-' && document.getElementById('AG-'+value._id.$oid).className == 'GOAL') { document.getElementById('AG-'+value._id.$oid).className = 'OLD-GOAL'; } if (prefixes[i] == 'HG-' && document.getElementById('HG-'+value._id.$oid).className == 'OLD-GOAL') { document.getElementById('HG-'+value._id.$oid).className = ''; } if (prefixes[i] == 'AG-' && document.getElementById('AG-'+value._id.$oid).className == 'OLD-GOAL') { document.getElementById('AG-'+value._id.$oid).className = ''; } if (prefixes[i] == 'HPI-' && values[i] < 7) { class_n = document.getElementById('HT-'+value._id.$oid).classList; class_n.remove('HI-PRESSURE'); } if (prefixes[i] == 'API-' && values[i] , 7) { class_n = document.getElementById('AT-'+value._id.$oid).classList; class_n.remove('HI-PRESSURE'); } //console.log('ya'); document.getElementById(prefixes[i]+value._id.$oid).innerHTML = values[i]; } } } }); var myGames = []; var cl = ''; var n = []; var table = document.getElementById("in-play"); for (var i = 0, row; row = table.rows[i]; i++) { //iterate through rows //rows would be accessed using the "row" variable assigned in the for loop if (row.className == 'even') { n = row.id.split('-'); cl = n[n.length - 1]; myGames.push(cl); //console.log(cl); } } //console.log(myGames); for(var i = 0; i < myGames.length; i++) { if (Curr.indexOf(myGames[i]) === -1 && myGames[i] != ""){ //console.log(myGames[i]); var row = document.getElementById('HT-'+myGames[i]); if (row != null) { row.parentNode.removeChild(row); } row = document.getElementById('AT-'+myGames[i]); if (row != null) { row.parentNode.removeChild(row); } var tr = document.getElementsByClassName('market-'+myGames[i]); var table = document.getElementById('in-play'); for(var i = tr.length - 1; i >= 0; i--){ table.deleteRow(tr[i].rowIndex); } tr = document.getElementsByClassName('form-'+myGames[i]); table = document.getElementById('in-play'); for(var i = tr.length - 1; i >= 0; i--){ table.deleteRow(tr[i].rowIndex); } } } }); }, 5000); Thank you for your time.
Divide two Inputs and multiply 100
I have the two functions match and and total working properly. I want the function total project match to divide the first function over the second function multiply times 100. the last function isn't working! Here is my code so far : matchContribution.subscribe(function (newValue) { if (newValue != undefined && newValue != '') { matchContribution(formatInt(newValue)); var dataValue = Number(matchContribution().replace(/\,/g, '')); if (dataValue > 999999999999.99 || dataValue < 0) { matchContribution(''); } if (loading == false) { sendCommand('SAVE'); } } }); var totalProjectCost = ko.computed(function () { var total = 0; var hasUserInput = false; if (grantRequest() != '' && grantRequest() != undefined) { hasUserInput = true; total = total + Number(String(grantRequest()).replace(/\,/g, '')); } if (matchContribution() != '' && matchContribution() != undefined) { hasUserInput = true; total = total + Number(String(matchContribution()).replace(/\,/g, '')); } if (total == 0) { if (!hasUserInput) return ''; else return formatInt('0'); } else { if (loading == false) { sendCommand('SAVE'); } return formatInt(total); } }); var totalProjectMatch = matchContribution()/totalProjectCost(); if(totalProjectMatch>=0) totalProjectMatch = Math.floor(totalProjectMatch); else totalProjectMatch = Math.ceil(totalProjectMatch);
var totalProjectMatch = ko.computed(function () { var total = 0; var hasUserInput = false; if ((grantRequest() != '' && grantRequest() != undefined) && (matchContribution() != '' && matchContribution() != undefined) && (totalProjectCost() != '' && totalProjectCost() != undefined)) { hasUserInput = true; total = Number(String(matchContribution()).replace(/\,/g, '')) / Number(String(totalProjectCost()).replace(/\,/g, '')); total = total * 100; } if (total == 0) { if (!hasUserInput) return ''; else return formatInt('0'); } else { if (loading == false) { sendCommand('SAVE'); } return formatNumber(total); } }); I solved the problem! Thanks a lot! Hope that helps other people.
Is it possible to replace two opposite and different functions with a single one?
I want to optimise and reduce my code to increase performance and correct-ability of it. With those two different functions below I can successfuly move a Google Map Marker on a map forward and backward using a pathIndex, calcuted on an array of GPS coordinates [I didn't include this section of code since I think it's not releated to this question but I can and will post it if needed]. This is my code: 1st function: function animate() { if (pathIndex < coord.length && mapAnimationStatus != PLAY_PAUSED) { googleMapsMarker.setPosition(coord[pathIndex]); googleMap.panTo(coord[pathIndex]); pathIndex += 1; if (pathIndex == coord.length) { pause(); pathIndex = 0; mapAnimationStatus = NOT_PLAY; return; } timerHandler = setTimeout("animate(" + pathIndex + ")", 1000); } } 2nd function: function animateRewind() { if (pathIndex >= 0 && mapAnimationStatus != PLAY_PAUSED) { googleMap.panTo(coord[pathIndex]); googleMapsMarker.setPosition(coord[pathIndex]); if (pathIndex == 0) { pause(); mapAnimationStatus = NOT_PLAY; return; } pathIndex -= 1; timerHandler = setTimeout("animateRewind(" + pathIndex + ")", 1000); } } As you can see those two functions shares a lot of portions of code and it think that they can be replaced with a single one for this reason but I can't figure out how to do this. So, is it possible to create a single function to manage those two different animations?
I hope I didnt miss something... function animate(pathIndex, dir) { var animateDir = (pathIndex < coord.length && mapAnimationStatus != PLAY_PAUSED && dir == 'f') ? dir : (pathIndex >= 0 && mapAnimationStatus != PLAY_PAUSED && dir == 'r') ? dir : "error"; if (animateDir === "r") { googleMap.panTo(coord[pathIndex]); } if (animateDir !== 'error') { googleMapsMarker.setPosition(coord[pathIndex]); } if (animateDir === "f") { googleMap.panTo(coord[pathIndex]); pathIndex += 1; } if (animateDir !== 'error') { if (pathIndex == coord.length || pathIndex == 0) { pause(); pathIndex = animateDir === "f" ? 0 : pathIndex; mapAnimationStatus = NOT_PLAY; return; } pathIndex = animateDir === "f" ? pathIndex - 1 : pathIndex; timerHandler = setTimeout("animate(" + pathIndex + "," + animateDir + ")", 1000); } }
You can try this : function ConcatenateFunctions() { if(mapAnimationStatus != PLAY_PAUSED){ googleMap.panTo(coord[pathIndex]); googleMapsMarker.setPosition(coord[pathIndex]); if (pathIndex < coord.length) { pathIndex += 1; if (pathIndex == coord.length) { pause(); pathIndex = 0; mapAnimationStatus = NOT_PLAY; return; } }else if (pathIndex >= 0) { if (pathIndex == 0) { pause(); mapAnimationStatus = NOT_PLAY; return; } pathIndex -= 1; } timerHandler = setTimeout("ConcatenateFunctions(" + pathIndex + ")", 1000); } } Hope it will help !
For Loop in JavaScript - Lottery Website
I am trying to turn this code into a correct for loop statement, so that I can save my repetitions. I have tried my best to get it done, but I just don't know how I can write it correctly: function myProg() { var luckyNumber = 3; var luckyNumber2 = 5; var luckyNumber3 = 8; var firstInput = document.luckForm.numberBox.value; var secondInput = document.luckForm.numberBox2.value; var thirdInput = document.luckForm.numberBox3.value; var temp = ''; if (firstInput == luckyNumber && secondInput == luckyNumber2 && thirdInput == luckyNumber3 || firstInput == luckyNumber && secondInput == luckyNumber3 && thirdInput == luckyNumber2 || firstInput == luckyNumber2 && secondInput == luckyNumber3 && thirdInput == luckyNumber || firstInput == luckyNumber2 && secondInput == luckyNumber && thirdInput == luckyNumber3 || firstInput == luckyNumber3 && secondInput == luckyNumber && thirdInput == luckyNumber2 || firstInput == luckyNumber3 && secondInput == luckyNumber2 && thirdInput == luckyNumber) { alert('Congratulations! You got all 3 numbers correct. You\'ve won £1000!'); } }
try something like this: Array.prototype.getDuplicates = function() { var cache = {}, results = [], that = this; that.forEach(function(item, index) { if(!cache.hasOwnProperty(item) && that.lastIndexOf(item) > index) { results.push(item); } cache[item] = true; }); return results; } var answers = [luckyNumber, luckyNumber2, luckyNumber3]; var indexes = [answers.indexOf(firstInput), answers.indexOf(secondInput), answers.indexOf(thirdInput)]; if(indexes.indexOf(-1) === -1 && indexes.getDuplicates().length === 0) { // alert("Whatever"); }
Here's an example without using array. Input check was added. function myProg() { var numbersToMatch = 3; var luckyNumbers = {n1: 3, n2: 5, n3: 8}; var firstInput = parseInt(document.luckForm.numberBox.value); var secondInput = parseInt(document.luckForm.numberBox2.value); var thirdInput = parseInt(document.luckForm.numberBox3.value); if (isNaN(firstInput) || isNaN(secondInput) || isNaN(thirdInput)) { alert('All inputs must be numbers!'); return; } var inputs = {n1: firstInput, n2: secondInput, n3: thirdInput}; var matches = {n1: false, n2: false, n3: false}; for (var i in inputs) { for (var j in luckyNumbers) { if ((!matches[j]) && (luckyNumbers[j] == inputs[i])) { matches[j] = true; numbersToMatch--; break; } } } if (numbersToMatch == 0) { alert('Congratulations! You got all 3 numbers correct. You\'ve won £1000!'); } }
Why will my Javascript not run in IE
Below is my code. It is supposed to filter a table. It functions great in everything but IE. Can you help? Perhaps there is a missing tag or something. I've been over it a number of times and could really do with someone's help please! <script type="text/javascript"> function hasPath(element, cls) { return (' ' + element.getAttribute('pathway')).indexOf(cls) > -1; } function hasLevel(element, cls) { return (' ' + element.getAttribute('level')).indexOf(cls) > -1; } function hasBody(element, cls) { return (' ' + element.getAttribute('body')).indexOf(cls) > -1; } function QualificationSearch() { var imgdiv = document.getElementById("Chosen_Pathway_img"); var p = document.getElementById("PathwaySelect"); var pathway = p.options[p.selectedIndex].value; if (pathway == "ALLPATHS") { pathway = ""; imgdiv.src = "/templates/superb/images/QualChecker/pic_0.png" } if (pathway == "ES") { imgdiv.src = "/templates/superb/images/QualChecker/pic_1.png" } if (pathway == "HOUSING") { imgdiv.src = "/templates/superb/images/QualChecker/pic_2.png" } if (pathway == "PLAYWORK") { imgdiv.src = "/templates/superb/images/QualChecker/pic_3.png" } if (pathway == "SC") { imgdiv.src = "/templates/superb/images/QualChecker/pic_4.png" } if (pathway == "YW") { imgdiv.src = "/templates/superb/images/QualChecker/pic_5.png" } var a = document.getElementById("AwardingBodySelect"); var awardingBody = a.options[a.selectedIndex].value; if (awardingBody == "ALLBODIES") { awardingBody = ""; } var levelGroup = document.getElementsByName("LevelGroup"); var chosenLevel = "" for (var g = 0; g < levelGroup.length; g++) { if (levelGroup[g].checked) { chosenLevel += levelGroup[g].value + " "; } } if (chosenLevel == undefined) { var chosenLevel = ""; } else { var splitLevel = chosenLevel.split(" "); var levelA = splitLevel[0]; var levelB = splitLevel[1]; var levelC = splitLevel[2]; var levelD = splitLevel[3]; if (levelA == "") { levelA = "NOLVL" } if (levelB == "") { levelB = "NOLVL" } if (levelC == "") { levelC = "NOLVL" } if (levelD == "") { levelD = "NOLVL" } } var fil = document.getElementsByName("QList"); for (var i = 0; i < fil.length; i++) { fil.item(i).style.display = "none"; if ((hasBody(fil.item(i), awardingBody) == true || awardingBody == "") && (hasPath(fil.item(i), pathway) == true || pathway == "") && ((hasLevel(fil.item(i), levelA) == true || hasLevel(fil.item(i), levelB) == true || hasLevel(fil.item(i), levelC) == true || hasLevel(fil.item(i), levelD) == true) || chosenLevel == "")) { fil.item(i).style.display = "block"; } } } </script>
Check your semicolons. IE is far more strict on that kind of stuff than FF.