making 3 different actions based on 3 different results - javascript

so i have this
client.on("chat", async (channel, userstate, message, self) => {
console.log(`Received message: ${message} from user ${userstate.username}`);
if (self) return;
if (userstate.username === "funtoon") {
const catchRegex = /!catch (.*)/;
const match = message.match(catchRegex);
if (match && match[1]) {
const response = await axios.get(
"https://grynsoft.com/spos-app/?c=Vod_Kanakas&u=Vod_Kanakas"
);
const $ = cheerio.load(response.data);
const textRegex = new RegExp(
`<b style="color: yellow;">${match[1]}<\/b>`
);
const textMatch = $("html").html().match(textRegex);
if (textMatch) {
console.log("Both style and match[1] are present");
} else if (match[1]) {
console.log("Only match[1] present");
} else {
console.log("Neither was present");
}
}
}
});
expected results are
if match[1] and style are present in the same element do nothing
if only match[1] is present in the element Only match[1] present
if neither match[1] nor style are present 'Neither was present"
test results are
Both style and match[1] are present, doing nothing
Only match[1] present
Only match[1] present
i dont want to perform random releases if i dont have them to begin with. how do i make it so 3 works right without breaking the others?
tried using chatgpt but to fix this but nothing i gave me worked.

I'd changed the last if/elses statement to :
[...]
const textMatch = $('html').html().match(textRegex);
if (textMatch && textMatch[0].includes(`style="color: yellow;"`)) {
console.log("Both style and match[1] are present");
} else if (textMatch) {
console.log("Only match[1] present")
} else {
console.log("Neither was present")
}
[...]
});

Related

If true return a string else return another string

Code contains errors: Uncaught SyntaxError: Unexpected token 'if' at undefined:18:22
When uploading to greasyfork I've got that error.
The javascript file is:
// ==UserScript==
// #name Docubuilder
// #namespace Editors
// #match *://*
// #grant none
// #version 1.0
// #author Josiah
// #description Josiah's Docubuilder builds anything on the current document. This also works on HTML files!
// ==/UserScript==
console.log("Starting to make builder's button so hang on!")
function buildermain() {
tobuild = prompt("Insert any valid HTML element, cancel or input nothing and a tab will open with a list of HTML elements.")
if (tobuild == '' || tobuild == null) {
window.open("https://developer.mozilla.org/en-US/docs/Web/HTML/Element")
} else {
mynew = document.createElement(tobuild)
myhtml = prompt("Text to display...")
mynew.innerHTML = if (!(myhtml == null)) { return myhtml } else { return 'A random ' + tobuild + '.'}
document.body.insertBefore(mynew, null)
alert("Done! Check the bottom of the page!")
}
}
const builderbutton = document.createElement('button')
builderbutton.onClick = "buildermain()"
builderbutton.innerHTML = "Start building some stuff!"
document.body.insertBefore(builderbutton, document.body.firstChild)
Maybe it was the if, so I'm trying to find a way to return a string to a variable in a single line.
Any help here?
Conditional (ternary) operator may help:mynew.innerHTML = (!(myhtml == null)) ? myhtml : 'A random ' + tobuild + '.';
The problem is that if() does not return a value. It will not assign a value to the property innerHTML.
There are some options to solve this.
Create a function
function buildermain() {
// [...]
mynew.innerHTML = getHtml(myhtml, tobuild);
// [...]
}
const getHtml = (myhtml, tobuild) => {
if (myhtml !== null) {
return myhtml;
}
return `A random ${tobuild}.`;
}
Use the ternary operator
function buildermain() {
// [...]
mynew.innerHTML = myhtml !== null ? myhtml : `A random ${tobuild}.`;
// [...]
}
Use if, else (correct) without direct assignemt to innerHtml
function buildermain() {
// [...]
if (myhtml !== null) {
mynew.innerHTML = myhtml;
} else {
mynew.innerHTML = `A random ${tobuild}.`;
}
// [...]
}

Basic comparison statement in javascript

So I'm trying to run a comparison statement with the firebase SDK.
I've got a function which checks if the phone number or email has a valid invite value / document exists within the database.
I want to add a comparison that says if the invitationData is valid and the claimedDate value is not equal to the data type null or the invitationData is valid and the string value is not equal to null then alert invitation not confirmed. The problem I'm having is with the || or operator I can only seem to get this comparison to work if I'm just doing one argument when I add the or it stops working.
async function checkInvitation(email = '', phone = '') {
try {
let snapshot = firebase.firestore().collection(COLLECTIONS.INVITATIONS);
if (email) {
snapshot = snapshot.where('email', '==', email);
} else if (phone) {
snapshot = snapshot.where('phone', '==', phone);
}
let invitationData = await snapshot.get();
if (!invitationData || invitationData.docs.length === 0) {
Alert.alert(
'Invitation not confirmed',
'Please try again or join our waiting list.',
);
return false;
}
if ((invitationData && invitationData.docs[0].data().claimedDate !== null) || (invitationData && invitationData.docs[0].data().claimedDate != "somestring")) {
Alert.alert(
'Invitation not confirmed',
'This invitation has already been used',
);
return false;
}
return invitationData.docs[0].id;
} catch (error) {
console.log(error);
throw new Error(error);
}
}
If you shorten it (excuse the pseudo nature) it looks as follows :
if (claimedDate !== null || claimedDate != "somestring")
I'm pretty sure that's not what you are meaning. Perhaps you are intending an AND?

Strange problem when Using REGEX in my nodeJs app

I have a doc which is a message in microsoft graph db and i am trying to parse some token / tracking nbr from the body. So in my case i get the info and then i pass the body to my regex function. And there is my problem, when i use
const str = messages.value[0].body
console.log(str)
// check if we have a tracking id in the body
const trackingId = regex.getTrackingId(str)
if(trackingId){
console.log('We have a Tracking ID ' + trackingId)
}
it fails here is my getTrackingId function
function getTrackingId(body) {
try {
console.log(body)
const regex = /http:\/\/demo.example.com\/campaign\/(.+)\/tracker.png/gm;
while ((m = regex.exec(body)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
console.log(m)
if (m.length == 2) {
return m[1]
} else {
return null
}
}
} catch (error) {
console.log(error) }}
i made sure the text is past to the function and thats the case. if i take the body and make it static it works so realy not sure whats going on ?
const str = `{ contentType: 'html',
content:
'<html>\r\n<head>\r\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\r\n<meta content="text/html; charset=us-ascii">\r\n</head>\r\n<body>\r\n<p>This is a Test Email which will be deleted</p>\r\n<img src="http://demo.example.com/campaign/xHMmLOSEpv/tracker.png">\r\n</body>\r\n</html>\r\n' }
"`;
function getTrackingId(body) {
try {
const regex = /http:\/\/demo.example.com\/campaign\/(.+)\/tracker.png/gm;
while ((m = regex.exec(body)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
if (m.length == 2) {
console.log('Tracking Nbr : ' + m[1])
} else {
console.log('No Tracking Nbr')
}
}
} catch (error) {
console.log(error)
}
}
getTrackingId(str)
After digging a little deeper i found the issue. My RegEx code is fine. The problem is that when i get the response from Microsoft API and assign it to the str variable it sees it as an object. Since Regex does not like that it never matches anything.
So the simple fix was to to
const str = JSON.stringify(messages.value[0].body)
i got to it when i tried to do a simple indexOf on str and got errors.

condense if, else JS with similar condition rules

trying to find a way to condense this. wasnt sure of the best way to do it. basically if criteria is met i display an alert with a parameter that is the message. i was thinking of maybe trying it in function. this is part of a larger function react component. i was also thinking if i could find a way to condense the else if's i could use a ternary. thanks in advance for the assistance.
const handleUpdatePassword = () => {
const allFilled = !reject(passwords).length;
const passwordsMatch = newPassword === conPassword;
const isDifferent = curPassword !== newPassword;
const meetsPasswordRequirements = validatePassword();
const usesName = isUsingName();
const usesUserID = isPartOfUserID();
const isValidPassword = meetsPasswordRequirements && isDifferent;
if (allFilled) {
if (!isDifferent) {
Alert.alert(difPassWord);
} else if (!passwordsMatch) {
Alert.alert(noMatch);
} else if (!meetsPasswordRequirements) {
Alert.alert(pasReqs);
} else if (usesName || usesUserID) {
Alert.alert(pasName);
}
} else {
Alert.alert(fieldNotComplete);
}
if (isValidPassword) {
changePasswordPost(
{
userId,
curPassword,
newPassword
},
partyId
);
}
};
You can create an array of objects for your validation rules, each containing a function which returns a boolean indicating whether that validation passes, and a string with the error message to display.
Then loop over the rules array and alert the message for the first rule that returns false. If they all return true, do the post.
You can split each if statement into a function, then chain them. For example
// here we make a closure to validate, and return a Promise
// condition can be a function
const validate = (condition, error) => ()=> new Promise((res, rej)=>{
if(condition()){
res();
}else{
rej(error);
}
});
const handleUpdatePassword = () => {
const validateFieldsComplete = validate(
()=>!reject(passwords).length,
fieldNotComplete
);
const validateDifPassword = validate(
()=> curPassword !== newPassword,
difPassWord
);
// ...
validateFieldsComplete()
.then(validateDifPassword)
.then(...)
.catch(Alert.alert)
}
It would be much cleaner with pipe. You can take a look at ramda. Or if you are intrested in functional way, you might consider using Monad.
I'd recommend DRYing up the Alert.alert part since all branches have that in common, and just come up with an expression that evaluates to the alert message. Compactness isn't always everything, but if you want it, then nested conditional operators can fit the bill. I'm also rearranging your conditions so that it can be a flat chain of if/elses:
const message
= reject(passwords).length ? fieldNotComplete
: curPassword === newPassword ? difPassWord
: newPassword !== conPassword ? noMatch
: !validatePassword() ? pasReqs
: (isUsingName() || isPartOfUserID()) ? pasName
: null;
const isValid = !message;
if (!isValid) {
Alert.alert(message);
}
(feel free to use any other sort of code formatting pattern; nested conditionals always look awkward no matter which pattern you use, IMO.)
Edit:
Also inlined conditionals which will short-circuit evaluation and make it even more compact.
I'd setup a validations object that has the tests and error messages and then loop over it. If validation fails, it'll throw the last validation error message. Using this method, you only have to maintain your tests in one place and not mess with a block of conditional statements.
const handleUpdatePassword = () => {
const validations = {
allFilled: {
test() {
return newPass && oldPass
},
error: 'Must fill out all fields'
},
correct: {
test() {
return curPass === oldPass
},
error: 'Incorrect password'
},
[...]
}
const invalid = () => {
let flag = false
for (let validation in validations) {
if (!validations[validation].test()) {
flag = validations[validation].error
}
}
return flag
}
if (invalid()) {
Alert.alert(invalid())
} else {
changePasswordPost(
{
userId,
curPass,
newPass
},
partyId
)
}
}
hi everyone this was the method i used for a solution
const messages = [
{
alertMessage: difPassWord,
displayRule: different()
},
{
alertMessage: noMatch,
displayRule: match()
},
{
alertMessage: pasReqs,
displayRule: validatePassword()
},
{
alertMessage: pasName,
displayRule: !isUsingName() || !isPartOfUserID()
}
];
if (allFilled) {
const arrayLength = messages.length;
for (let i = 0; i < arrayLength; i++) {
if (messages[i].displayRule === false) {
Alert.alert(messages[i].alertMessage);
}
}

What location.hash.match return if there is no hash?

please can you tell me what does location.hash.match return if there is no hash ?
My code :
function getHashValue(key) {
return location.hash.match(new RegExp(key + '=([^&]*)'))[1];
}
test = getHashValue('test');
if (test == 'abc') {
//code WORKS
}
else if (test == 'sal') {
//code WORKS
}
else if (test == "") {
//code DOESNT WORKS
}
but It doesn't works
I forget to mentionned that my code 'getHashValue' return the value of the hash Exemple : #test=abc
sorry I forget to mentionned it
Why not just?
test = getHashValue('test');
if (test === undefined) {
//code
}
EDIT
The error was from a null return in the match() call. The following change will return an empty string if the match is "" or null.
function getHashValue(key) {
var match = location.hash .match(new RegExp(key + '=([^&]*)'));
return match ? match[1] : "";
}
If you run location.hash in your browser console on any website where you're not using a hash, you'll find that it returns the empty string "".
As such, a regex match on that will find 0 results, returning null, at which point, you try to access null[1]...
location.hash will be empty string and your function:
function getHashValue(key) {
return location.hash.match(new RegExp(key + '=([^&]*)'))[1];
}
Will indeed return undefined. The problem is that you are checking "undefined" value incorrectly. Change your code to:
test = getHashValue('test');
if (typeof(test) === 'undefined') {
//code
}

Categories

Resources