Im getting error Unexpected constant condition no-constant-condition when trying to build this code. (Error is on line indicated with >>>)
The code runs off a user input, commandVariable0 & commandVariable1 take data from the input, in this case b2b on or b2b off, if they user should put b2b test then it should give the error warning: commandVariable1 is not a valid settings option.
Can anyone help me understand why this is not working, if a user puts b2b test it accepts it as valid.
Any help would be appriciated.
const b2b = function(data)
{
const commandVariable0 = data.cmd.params.split(" ")[0].toLowerCase();
const commandVariable1 = data.cmd.params.split(" ")[1].toLowerCase();
>>> if (commandVariable1 === "on"||"off")
{
b2bvar = commandVariable1;
var output =
"**```Bot 2 Bot Command Here```**\n" +
`Embeded Messages : ${b2bvar}\n\n` +
`Command Variable 0 : ${commandVariable0}\n` +
`Command Variable 1 : ${commandVariable1}\n`;
data.color = "info";
data.text = output;
return botSend(data);
}
data.color = "error";
data.text =
":warning: **`" + commandVariable1 +
"`** is not a valid settings option.";
return botSend(data);
};
Please ignore the sloppy code.
Change your line
if (commandVariable1 === "on"||"off")
to
if (commandVariable1 === "on" || commandVariable1 === "off")
What's the problem?
In the above line JavaScript will first check if commandVariable1 equals "on" and if not then it will convert "off" into a boolean and check if that's true.
Since the string "off" is a constant and will always result to true in JavaScript, your linter will complain about the unneccessary OR condition.
Related
I'm trying to make a Discord bot and will apply commands from JSON file (for ex. if command is "abc", find "abc" in commands' array (list) and reply with abc's data). Here an element from my JSON file (file is long, because of this, haven't put full file):
[
{"howareyou": {
"Reply": "**Uh, oh... A few minutes ago lost my diamond banana from Middle Ages. But expect this, I'm OK.",
"NoArguments": true
}}
]
But the problem is: I get error "Cannot read property "Reply" of undefined" at this JS code:
const CMDFile = JSON.parse (FS.readFileSync ('./Commands.json', 'utf8', Error_ => { if (Error_) throw Error_ }))
if (Message.content.startsWith ('\\')) { // My prefix is '\'
if (Used_CMD == '' /* Used CMD is msg content without prefix */ || (Message.mentions.users.first () && Message.mentions.users.first ().id == '123456789012345678')) {
Cevapla ('Yes, I'm! For more, just use command `\\help`.')
} else {
const CMD = CMDFile [Used_CMD],
Reply = CMD.Reply, NoArg = CMD.NoArguments
My code runs correctly when I use '\' command btw, but when I type '\howareyou', it errors TypeError: Cannot read property 'Reply' of undefined. How can I fix this? Thanks.
The problem is either the format of your input file, or the code to get the proper command from the JSON.
either change your input file to :
{
"howareyou": {
"Reply": "**Uh, oh... A few minutes ago lost my diamond banana from Middle Ages. But expect this, I'm OK.",
"NoArguments": true
},
"other_cmd": {
"Reply": "xx",
"NoArguments": true
}
}
or find the command from the current structure :
var CMD = null
CMDFile.forEach((cmd) => { if(cmd.hasOwnProperty(Used_CMD)) CMD = cmd; });
or (as per comment)
const CMD = CMDFile.find(cmd => cmd.hasOwnProperty(Used_CMD));
I am trying to compare two strings using JavaScript, and I am honestly stumped as to why this is not working for me. I've tried using ==, ===, localeCompare(), adding spaces, converting it to lowercase, and nothing is working! Here is my code (from my content script)
var longBrand = byline.innerHTML;
var brand = longBrand.substring(7);
console.log(brand);
if(brand){
console.log("It can read inside this statement");
var lowerBrand = brand.toLowerCase();
console.log(lowerBrand);
if(lowerBrand === "nike" || lowerBrand === " nike" || lowerBrand === " nike"){
console.log("testing");
}
}
The variable brand comes from a substring of longBrand, which is taken from a webpage. The console shows everything is logged except for the last console.log("testing"); and I can't figure out why that is. Console looks like this:
Nike
It can read inside this statement
nike
I've even double checked that typeof brand is a string. I don't know what's going wrong here! Any help would be greatly appreciated!
Well, it works good here. Maybe your variable brand isn't "Nike". Try to do:
brand = brand.trim(); to remove white spaces.
// var longBrand = byline.innerHTML;
// var brand = longBrand.substring(7);
const brand = "Nike"
if(brand){
console.log("It can read inside this statement");
const lowerBrand = brand.toLowerCase();
console.log(lowerBrand);
if(lowerBrand === "nike" || lowerBrand === " nike" || lowerBrand === " nike"){
console.log("testing");
}
}
So I am goofing off and wrote something that first queries other websites and loads all of the pertinent stock exchange symbols and the tries to iterate through the symbols and load Yahoo's server for the latest stock price. For some reason no matter what I try to search by using HtmlAgilityPack, I can't seem to get any pertinent info back. I don't think there's an issue with some javascript running after the page is loaded (but I could be wrong).
The following is a generalized routine that can be tinkered with to try and get the percentage change of the stock symbol back from Yahoo:
string symbol = "stock symbol"
string link = #"http://finance.yahoo.com/q?uhb=uh3_finance_vert&s=" + symbol;
string data = String.Empty;
try
{
// keep in this scope so wedget and doc deconstruct themselves
var webget = new HtmlWeb();
var doc = webget.Load(link);
string percGrn = doc.FindInnerHtml("//span[#id='yfs_pp0_" + symbol + "']//b[#class='yfi-price-change-up']");
string percRed = doc.FindInnerHtml("//span[#id='yfs_pp0_" + symbol + "']//b[#class='yfi-price-change-down']");
// create somthing we'll nuderstand later
if ((String.IsNullOrEmpty(percGrn) && String.IsNullOrEmpty(percRed)) ||
(!String.IsNullOrEmpty(percGrn) && !String.IsNullOrEmpty(percRed)))
throw new Exception();
// adding string to empty gives string
string perc = percGrn + percRed;
bool isNegative = String.IsNullOrEmpty(percGrn);
double percDouble;
if (double.TryParse(Regex.Match(perc, #"\d+([.])?(\d+)?").Value, out percDouble))
data = (isNegative ? 0 - percDouble : percDouble).ToString();
}
catch (Exception ex) { }
finally
{
// now we need to check what we have and load into the datgridView
if (!newData_d.ContainsKey(symbol)) newData_d.Add(symbol, data);
else MessageBox.Show("ERROR: Duplicate stock Symbols for: " + symbol);
}
And here is the extended method for FindInnerHtml:
// this is for the html agility class
public static string FindInnerHtml( this HtmlAgilityPack.HtmlDocument _doc, string _options)
{
var node = _doc.DocumentNode.SelectSingleNode(_options);
return (node != null ? node.InnerText.ToString() : String.Empty);
}
Any help with getting something back would be appreciated, thanks!
///////////////////////////////////////
EDIT:
///////////////////////////////////////
I highlighted the span id and then check out line 239 for where I saw 'yfi-price-change-up' reference:
The following XPath successfully find the target <span> which contains percentage of increase (or decrease) :
var doc = new HtmlWeb().Load("http://finance.yahoo.com/q?uhb=uh3_finance_vert&s=msft");
var xpath = "//span[contains(#class,'time_rtq_content')]/span[2]";
var span = doc.DocumentNode.SelectSingleNode(xpath);
Console.WriteLine(span.InnerText);
output :
(0.60%)
I'm fairly new to GAS and Javascript in general and have searched far and wide to find an answer to why this isn't working, but haven't found a solution. I was wondering if one of you guys could find the problem. Here's my code:
function maintenanceRequest() {
var findFirstRequest = GmailApp.search("to:censored label:ems-request AND is:unread", 0, 1)[0];
var firstRequest = findFirstRequest.getMessages()[0];
var parseRequest = firstRequest.getPlainBody();
var requestString = String(parseRequest);
if ("Mark archived mail as read" == requestString) {
markArchivedAsRead();
findFirstRequest.moveToArchive();
}
else if ("Cleanup" == requestString) {
weeklyCleanup();
findFirstRequest.moveToArchive();
}
else {
GmailApp.sendEmail("censored", "Failure to parse command", "The EMS has recieved your request but has failed to recognize the command '" + parseRequest + "'. Please try again, using the terms 'Mark archived as read' or 'Cleanup'. If you would like to add an eligible command, please refer to function 'maintenanceRequest'.", {
name: "Email Maintenance Service",
from: "censored"
})
//Add moveToArchive line here after debugging
}
}
The code always skips the if and else if statements and jumps to the else statement, regardless of the email's content. I've tried using both == and === to no avail, and have tried switching the sides that the arguments are on. To no avail. I even created a new var, requestString to convert parseRequest to a string, even though I'm like 99% certain that it already is a string.. so what gives? Where's the problem?
Try adding trim to the string: requestString = requestString.trim()
It's usually a safe bet to use trim on any string you're getting from another service.
I was just going through the code of timer.js HERE. and came across the following lines of code:
var paramList = ['autostart', 'time'];
for (var arg in paramList) {
if (func[paramList[arg]] != undefined) {
eval(paramList[arg] + " = func[paramList[arg]]");
}
};
In the source code its all on one line, but i've made it more readable above , my difficulty is with the usage of eval, I.E. the below line of code:
eval(paramList[arg] + " = func[paramList[arg]]");
now if i add a breakpoint in chrome to the above line and go to the console and paste the line of code i get the following:
true
How come ? lets have a close look at the statement again:
eval(paramList[arg] + " = func[paramList[arg]]");
what is the + doing here ? converting paramList[arg] to a string , in which case eval is being used as follows:
eval("paramList[arg] = func[paramList[arg]]");
?
or is the plus sign being used for concatenation purpose ? (which i think is very unlikely !)
I have read MDN eval(), but still had doubts.
can anybody explain the breakdown of that statement please ?
Thank you.
eval takes a string. What you have:
eval(paramList[arg] + " = func[paramList[arg]]");
The + is just string concatenation.
Is equivalent to:
var code = paramList[arg] + " = func[paramList[arg]]"
eval(code);
So I'd say it should be equivalent to:
global[paramList[arg]] = func[paramList[arg]];
Or, in this particular example (with var paramList = ['autostart', 'time'];)):
if (func['autostart'] != undefined)
autostart = func['autostart'];
if (func['time'] != undefined)
time = func['autostart'];