Page reading 2 different If-Statements as the same - javascript

I'm running into a pretty confusing situation here:
if ((a.length == 0 || b === null)) {
this.noNotif = true;
console.log("1");
}
if (a.length > 0 || b === null) {
this.newNotif = true;
// this.noNotif = false;
console.log("2");
} else {
if (a.length === b.length) {
console.log("No New Notifications");
this.noNotif = true;
} else {
console.log("New notifications");
this.newNotif = true;
}
Console logging a.length returns 0 and 'b' is null
However, the issue is that somehow both of the first two if-statements' conditions are being met. noNotif and newNotif both display a Vue components and both are showing up currently.
Some background information about a & b
'a' is supposed to be data from an API that is fetched on page load. 'b' is supposed to be a localStorage object array
The first if-statement deals with a new user who has no API data or anything stored in LocalStorage
The second if-statement handles when the user does have data in the API, but nothing in LS yet.
The First nested if-statement is if the data from the API matches the LS data
The nested else-statement is if the API data is different (longer) than what's in LS

EDITED:
It turns out you also didn't put an "else" statement between the two. They're both triggering because they're both registering the || b = null.
if ((a.length == 0 || b === null)) {
this.noNotif = true;
console.log("1");
} else if (a.length > 0 || b === null) {
this.newNotif = true;
// this.noNotif = false;
console.log("2");
} ...

Related

if it has footer.text it reacts, but I want it to do the opposite

what it does is add a reaction :pray: when an embed has footer.text, but I don't want that, I want it to react when it doesn't have a footer.text
if(message.embeds.length >= 0)
// Check if the Message has embed or not
{
let embed = message.embeds
// console.log(embed) just a console.log
for(let i = 0; i < embed.length; i++)
// Loop it since in v13 you can send multiple embed in single message
{
if (!embed[i] || !embed[i].footer || embed[i].footer.text === null) return;
// check each embed if it has footer.text or not, if it doesnt then do nothing
{
setTimeout(function(){
message.react(':pray:')
}, 1000);
}
}
}
You simply need to switch your conditions like so:
if (embed[i] || embed[i].footer || embed[i].footer.text !== null) {
setTimeout(function() {
message.react('๐Ÿ™')
}, 1000);
}
Where !== represents Strict Inequality so what you are actually doing is checking the following conditions
If there is an embed to the message
If that embed object has a footer
If the content of the footer is not empty
Further since all of these conditions are necessary I would suggest using Logical AND (&&) operator which only returns true if the checks of all operands are fulfilled, so your code would look something like this:
if (embed[i] && embed[i].footer && embed[i].footer.text !== null) {
setTimeout(function() {
message.react('๐Ÿ™')
}, 1000);
}

discord.js embeds: UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body embed.fields[0].value: Must be 1024 or fewer in length

I am creating a discord bot that will take data from a website, and display it in an embed.
I stored the data in an array called boxArr. Then I iterate over it, store the data temporarly, and assign it to the correct embed's fields' properties (namely title and value).
It works fine for some pages, but not for others. Whenever if fails, I get an
[UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body embed.fields[0].value: Must be 1024 or fewer in length.] warning.
However the embed's values never exceeds 1024 characters in length, so I am baffled as to why I am getting this warning.
Here is my code:
//Create the embed
var exampleEmbed = new Discord.MessageEmbed()
.setColor('#2D2D2D')
.setTitle(str)
.setURL('/*page link here*/'+str)
.setThumbnail(th)
.addField('โ€Œโ€Œ', def + `[Read More...](/*page link here*/${str})`);
//Variable to hold the decision if titles are even or odd
var toOdd = true;
for(i = 0; (boxArr[i] != undefined || boxArr[i] != null); i++) {
if(boxArr[i] === '' || boxArr[i].startsWith('"')) {
if(isOdd(i) === 1) { //If boxArr[i] is nothing and i is odd, titles' location is when i is even
toOdd = false;
continue;
} else { //If boxArr[i] is nothing and i is even, titles' location is when i is odd
toOdd = true;
continue;
}
}
if(toOdd) {
if(isOdd(i) === 1) {
title = boxArr[i]; //Assign title its value
i++; //Increment i
val = boxArr[i];
if(val === undefined || title === undefined) { //Check if one of the two is undefined. If yes then break out without tampering with the embed.
break;
}
Embed.addFields({name: title, value: val, inline: true});
if(boxArr[i+1] === undefined) { //This is unnecessary but I added it nevertheless
break;
}
continue;
}
} else if(!toOdd) { //Similar to if toOdd === true
if(isOdd(i) != 1) {
title = boxArr[i];
i++;
console.log('\n\nVALUE: '+ boxArr[i]);
val = boxArr[i];
if(val === undefined || title === undefined) {
break;
}
Embed.addFields({name: title, value: val, inline: true});
if(boxArr[i+1] === undefined) {
break;
}
continue;
}
}
}
message.channel.send(Embed); //send the embed
Any help is appreciated.
So I found the problem.
Apparently the problem is that the embed itself has over 1024 characters.
Removing [Read More...](/*page link here*/${str}) from .addField('โ€Œโ€Œ', def + [Read More...](/*page link here*/${str})); solved the problem.
EDIT: Another fix is to limit str to 500 characters.

Firebase: Query.on failed: Was called with 1 argument. Expects at least 2

The error is in the title.
The app Iยดm building is based on React and Firebase.
I am trying to use promises.
Here is my code:
gamesRef.on('value').then(function(snapshot){
// find all empty games
var gamesToRemove = [];
snapshot.forEach(game => {
if(game.val().player1 == ""
&& game.val().player2 == ""
&& game.val().player3 == ""
&& game.val().player4 == ""){
gamesToRemove.push(game.key());
}
});
return gamesToRemove;
}).then(function(gamesToRemove){
// remove all empty games
for(var index in gamesToRemove){
gamesRef.child(gamesToRemove[index]).remove();
}
}, function(error){
console.log(error);
});
I found this question on SO that addressed the same issue. The solution was that the Firebase version needs to be at least 2.4 to use promises. I used an older version, but after upgrading to 2.4.2, i still get the same error. What should I do?
Edit: Code after fix. Get error "gamesRef.on(...).then is not a function".
gamesRef.on('value', function(snapshot){
// find all empty games
var gamesToRemove = [];
snapshot.forEach(game => {
if(game.val().player1 == ""
&& game.val().player2 == ""
&& game.val().player3 == ""
&& game.val().player4 == ""){
gamesToRemove.push(game.key());
console.log("denna borde raderas: " + game.key());
}
});
return gamesToRemove;
}).then(function(gamesToRemove){
// remove all empty games
for(var index in gamesToRemove){
gamesRef.child(gamesToRemove[index]).remove();
}
});
You have wrong mindset about on+then,
on takes 2 arguments: the name for event, and callback, callback is just plain function which takes event as argument:
gamesRef.on('value', function(snapshot){
// find all empty games
var gamesToRemove = [];
snapshot.forEach(game => {
if(game.val().player1 == ""
&& game.val().player2 == ""
&& game.val().player3 == ""
&& game.val().player4 == ""){
gamesToRemove.push(game.key());
}
});
return gamesToRemove;
})
and then, you can use your then :D
While many function in the Firebase JavaScript client return a promise, on() is not one of them.
The reason for this is that on() will typically deliver a value multiple times, while the contract of a promise is that then() will resolve at most once.
If you only care about getting the value of the data once, you can use once() and a promise:
gamesRef.once('value').then(function(snapshot){
// find all empty games
var gamesToRemove = [];
snapshot.forEach(game => {
if(game.val().player1 == ""
&& game.val().player2 == ""
&& game.val().player3 == ""
&& game.val().player4 == ""){
gamesToRemove.push(game.key());
}
});
return gamesToRemove;
}).then(function(gamesToRemove){
// remove all empty games
for(var index in gamesToRemove){
gamesRef.child(gamesToRemove[index]).remove();
}
}.catch(function(error){
console.log(error);
});

true == false evaluates to true somehow?

I've been working to scrape some webpage that is using the OWASP CRSFGuard project for protection. The library seems to be causing one of my requests to get a 401 so I started digging through their code and noticed the following;
function isValidDomain(current, target) {
var result = false;
/** check exact or subdomain match **/
if(current == target || current == 'localhost') {
result = true;
} else if(true == false) {
if(target.charAt(0) == '.') {
result = current.endsWith(target);
} else {
result = current.endsWith('.' + target);
}
}
return result;
}
From what I can tell, there must be instances where this code is executed; result = current.endsWith('.' + target);. Given true == false is inherently false, how would the code reach that statement? Is this some JS oddity (I know we're not using the strict === equality, but seriously...)?
Answer: It will never reach that code block.
function isValidDomain(current, target) {
var result = false;
/** check exact or subdomain match **/
if (current == target || current == 'localhost') {
result = true;
} else if (true == false) {
if (target.charAt(0) == '.') {
result = current.endsWith(target);
} else {
result = current.endsWith('.' + target);
}
}
return result;
}
var trueFalse = document.getElementById('trueFalse');
trueFalse.innerHTML = isValidDomain('true', 'false') ? 'WTF!' : 'All is good in the JS World';
trueFalse.addEventListener('click', function(e) {
trueFalse.innerHTML = (true == false) ? 'WTF!' : 'All is good in the JS World Still';
});
<div id="trueFalse"></div>
I would say that Blazemonger is most likely correct.
That else if probably had some other condition at some point, and for whatever reason, they decided they didn't want that block of code to execute anymore, so they changed the condition to something that is always false.
It's also not entirely uncommon to see programmers use 1 === 0 as an indication for false. Why they would want to do this is anybody's guess.

better solution about JS nesting if statement

Let's say there are 3 divs in my html.
Id's are:
stepone
steptwo
stepthree
I want first to load in data which is json from server on stepone div, if the return is '1' then print good on stepone div.
Then load in data on steptwo div, the data is json as well. So basically this is the process and the following is my code:
$(document).ready(function(){
var loadingone = $.post("stepone.php");
.done(function(dataone){
objone = JSON && JSON.parse(dataone) || $.parseJSON(dataone); //get json return from server
if (objone.status == "1") {
$("#stepone").html("good");
var loadingtwo = $.post("steptwo.php")
.done(function(datatwo){
objtwo = JSON && JSON.parse(datatwo) || $.parseJSON(datatwo);
if (objtwo.status == "1"){
$("#steptwo").html("good");
}
else
{
$("#steptwo").html("bad");
}
});
}
else
{
$("#stepone").html("message" + objone.codeurl);
}
});
});
So as you can see the code contains nested if statement and it doesn't look very clear. I am wondering if there is a better solution for this? thx
===updata===
here's the code after i edited, is it right?
var loadingone = $.post("stepone.php");
.done(function(dataone){
objone = JSON && JSON.parse(dataone) || $.parseJSON(dataone);
if (objone.status != "1"){
$("#stepone").html("bad" + objone.codeurl")
}
else{
$("#stepone").html("good");
var loadingtwo = $.post("steptwo.php");
.done(function(datatwo){
objtwo = JSON && JSON.parse(datatwo) || $.parseJSON(datatwo);
if (objtwo.status != "1"){
$("#steptwo").html("bad");
}
else
{
$("#steptwo").html("good");
}
}
}
Negate your expressions.
Rather than following a pattern like:
if A {
if B {
if C {
do stuff
}
else error C
}
else error B
}
else error A
Try this:
if !A {
error A
return
}
if !B {
error B
return
}
if !C {
error C
return
}
do stuff
This way, you keep the errors with their respective conditions, and you avoid deep nesting.

Categories

Resources