If statement with logical or operator - javascript

I want my function to check to see if the status is 'closed' or 'complete' and if it is either of those to perform the action in brackets.
For some reason I can't seem to make that work, it will check closed but not check complete.
for (var id in games) {
if (games[id].league === 'NCAAB')
if ((games[id].status == 'complete')||(games[id].status == 'closed')) {
sports.clearTimer();
}
if (ts >= games[id].scheduledTimeUnix) { xxxxxx}
Right now the timer isn't being cleared despite the fact the only two status for the nodes are complete and closed. The XXXX represents api calls that occur and the function is constantly making those calls.

or check for the true, if it gets one true it will not check other condition and perform the action preceding it.
if ((games[id].status == 'closed')||(games[id].status == 'complete'))
so if you get
games[id].status == 'closed'
as true , it will not check for
(games[id].status == 'complete')

Related

Leaflet JS Visualization through static API response using JQuery

I'm getting a static response from an API (it returns the same data on every call) and based on that response I'm changing visualization properties of a GeoJSON object.
Currently my workflow is:
Read GeoJSON in frontend
Hit API to get its response
Loop through the api keys and match them with GeoJSON's key. Symbolize based on value when ID gets matched.
The issue with this approach is that on every event, I'm making a new request and getting the same data. Also, after getting the data, the loop takes lots of time to complete and then the visualization property gets applied.
I have tried storing API response in a variable in the frontend code as well but the time taken while looping through the ID's is still a lot. I can't think of any ways to store the visualization properties somewhere to make the symbology change of GeoJSON rapidly.
Some code example to implement this would be helpful. My current code is shared below:
$(".ambtn").on("click",function(){
$.ajax({
method:"get",
url:"/los_am",
beforeSend: function(){
$("#loader").css({
display: "inline-block",
visibility: "visible"
});
},
complete: function(){
$("#loader").css({
display: "none",
visibility: "hidden"
});
},
success:function(res){
// console.log(res)
rdNetworkLyr.eachLayer(function (layer) {
for (const key in res.XDSegID){
if(res.XDSegID.hasOwnProperty(key)){
if(layer.feature.properties.XDSegID === res.XDSegID[key] && res.los[key] === 'A'){
layer.setStyle({color:'#060'})
}
else if (layer.feature.properties.XDSegID === res.XDSegID[key] && res.los[key] === 'B'){
layer.setStyle({color:'#9f0'})
}
else if (layer.feature.properties.XDSegID === res.XDSegID[key] && res.los[key] === 'C'){
layer.setStyle({color:'#ff3'})
}
else if (layer.feature.properties.XDSegID === res.XDSegID[key] && res.los[key] === 'D'){
layer.setStyle({color:'#f90'})
}
else if (layer.feature.properties.XDSegID === res.XDSegID[key] && res.los[key] === 'E'){
layer.setStyle({color:'#f60'})
}
else if (layer.feature.properties.XDSegID === res.XDSegID[key] && res.los[key] === 'F'){
layer.setStyle({color:'#c00'})
}
}
}
});
}
});
});
My aim is to pass that stored symbology to "setStyle" function without having to loop every time the request is made.
the loop takes lots of time to complete
the time taken while looping through the ID's is still a lot
Unless you have millions of keys to loop through, the algo part in itself is rarely the bottleneck.
What may slow down things is the style change of individual layers in your GeoJSON Layer Group rdNetworkLyr: if that makes the browser recompute and repaint the entire Group at every individual change, for sure it will take a lot of work at every step, especially if your group is big!
You can try a simple workaround by removing your rdNetworkLyr Layer Group from the map first before applying all the individual style changes, then adding it back:
function (res) {
rdNetworkLyr.remove();
// Change all the styles
rdNetworkLyr.addTo(map);
}

Check if button has been pressed

I want to add an if statement that checks if the user is undefined for my program. It should alert: "no more profiles".
The problem is that my "likeId" is undefined to start with and I will get the alert first time i run the function. I would like to know that I can make an if statement that checks if a certain button has been pressed exactly one time.
This is my code:
if (localStorage.getItem('likeId') == "undefined"){
alert("no more profiles to swipe")
}
My code should look something like this:
if (localStorage.getItem('likeId') == "undefined" && Button has been clicked exactly one time){
alert("no more profiles to swipe")
}
Just add a counter when the function tied to the button is called. You then check if buttonClickedCounter == 1 and you should be good to go.

uncaught error data undefined on ajax call

I'm making an ajax call (JavaScript) which generates through the show info function the data I'm retrieving. My problem is as follows: On one of the arrays some data don't have it, there are not many but there is still some. So it's displaying the first items but it stops when it can't retrieve the said array and return a:
Uncaught TypeError: info["xxxx"] is undefined.
What I'd really like is to be able to make it so it still retrieve / display the datas and says something like 'this data.[denomination][0].title is undefined or anything else'.
I tried to use the optional chaining operator '?.' but I clearly have no idea on how it works.
Here's what makes me get crazy: (it's the data["denomination"] that ruins it all)
request.addEventListener('readystatechange', function(){
if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
const backCall=JSON.parse(request.responseText);
if(backCall.count != 0){
for(let data of backCall.datas){
showInfo(data.title, data["author"][0].name, data["denomination"][0].title, data["denomination"][0].id);
}
}else if(backCall.count === 0){
noResult();
}
}
});
(just a little edit to be precise. I searched before hand and even looked up to the advised subjects from Stack when I was writing this)
Check if both properties exist in the object and then call your showinfo function, it should not fail
for (let data of backCall.datas) {
if (data["author"] && data["denomination"]) {
showInfo(data.title, data["author"][0].name, data["denomination"][0].title, data["denomination"][0].id);
}
}

Detecting if I have already alerted a message

I have a page that loads some data into a model and one of the properties of the model has an errormessage. I have a js file that checks if the errormessage is there; if so, it displays an alert with the message itself like this:
function CheckErrMsg(model) {
if (model.CallStatusStatus() == -111) {
alert(model.CallStatusErrorMessage());
}
}
Whenever I'm done doing whatever with the object I have loaded it automatically loads another one and if this checks out for the new model then it will display the alert again.
I want the alert to be displayed only for the first model loaded, so I guess I need to know if there is a way to check if that alert was already displayed and if so don't display it again.
You can add an IsAlertShown field to the model then check it before alerting:
model.IsAlertShown = ko.observable(false);
if (!model.IsAlertShown() && model.CallStatusStatus() == -111) {
model.IsAlertShown(true);
alert(model.CallStatusErrorMessage());
}
Yet, personally I don't like to 'pollute' my View-Model (which is usually about to be sent back to the server) with stuff that are purely UI-related. So I would expose the flag as part of the function itself:
if (!CheckErrMsg.IsAlertShown && model.CallStatusStatus() == -111) {
CheckErrMsg.IsAlertShown = true;
alert(model.CallStatusErrorMessage());
}
(Since in JavaScript functions are also objects, you can set properties on functions as well)
Just set a flag:
messageDisplayed=0;
function CheckErrMsg(model) {
if (model.CallStatusStatus() == -111 && messageDisplayed==0) {
alert(model.CallStatusErrorMessage());
messageDisplayed=1;
}
}
That'll do the trick.

$.get() troubles before submitting page

Think a shopping basket with some "goods" in it.
I have a <li> list of elements and each of them has a field containing a number - the amount.
Conceptually this is what i want: When the user presses a button, i loop through each <li> element picking the amount. Then i do a $.Get() to call the server with the goods id + the amount to check if the store has enough of the particular item. The server replies either True og False.
This reply is temporary stored in a html field.
Now after the looping is done, i check if there were a False reply on any of the goods.
If so i highlight the "false" items. Or else i simply submit.
OK, the problem is that my code seams to continue past my $.get() call-back function, so the final check to see if any false was returned is evaluated before the $.get() actually receives a result from the server.
Anyway this is what i think is happening...
Now lets look at some code:
var tmp = new Array();
var id = '';
var c = '';
var n = 0;
var z=0;
$('#basket').find('li.list').each(function() {
c = $(this).find('input.fldamount').val(); // this is the amount field
id = $(this).attr('id'); // this is the id no of the item
$.get('./(RPC)?OpenAgent&cmd=movewhcheckamount&unid='+id+'&count='+c, function(data) {
$('#RPCResult').val(data); // i store the returned value in a html field
if ( $('#RPCResult').val() == "true" ) {
tmp.push( id+'|'+c ); // if true is returned, i push the id & amount to an array
} else {
$(this).addClass('red'); // else i tag the item
n=n+1; // and then increment a counter
}
} ); // $('#basket')
var t = window.setTimeout( function() {
if (tmp.length > 0 && n == 0) { // if i got items in the array AND my false counter is zero
$('#SelectedArtikler').val( tmp.join(";") ); // then i store the array as text in a field
document._FlyttArtikel.submit(); // and submit
} else if (n > 0) {
// show a popup
alert("You're trying to move more items than exists...");
} else {
alert("ops, nothing to move..."); // should never end up here...
}
}, 1000);
window.clearTimeout(t);
As you can see, i have tried to counter-act the code running past my call-back function with a setTimeout, so that i basically wait a sec to give the server time to respond.
I did have another loop around the setTimeout the continued as long as my #RPCResult field was empty, but that resulted in an infinite loop.
I have the #RPCResult field visible so i can see what happens and what i see is that the popup "You're trying to move more items..." is shown and RIGTH AFTER i press ok on that popup THEN the #RPCResult field gets the result true/false.
I now some of the code can be optimized but what i'm interested in right now is getting the $.get() result in a proper fashion.
Thanks in advance ;-)
You're going to have to place the code that's going to run when all the "$.get()" calls are finished inside the callback routine. That's the only place where you can be sure that you've actually gotten the server response(s). Keep a counter of how many calls have returned, and when the counter increments up to be equal to the total number of items, then you know that all of the responses are available.
Thus:
var basketSize = $('#basket').find('li.list').length, completed = 0;
gives you the number of items and initializes the counter. Inside the callback function passed to "$.get()" you can then do something like this:
if (++completed === basketSize) {
// code currently in the "setTimeout()" callback
}
Your code already appears to be doing some of this work (the "n" variable that you increment).
Now, that said, I'll also note that it's quite crazy to perform separate HTTP transactions for each of your "items". You should bundle them all up into one HTTP request that returns a list of answers.
Also, there's really no point at all in storing the response to the "$.get()" in that "RPCresult" field; just examine the value of "data", since nothing ever looks at "RPCresult" again anyway.

Categories

Resources