Skip to main content

Reverse a string

Nov 19, 2022CodeCatch
Loading...

More JavaScript Posts

Authenticate Discord User

Mar 28, 2023Helper

0 likes • 1 view

const Discord = require('discord.js');
const client = new Discord.Client();
const token = 'YOUR_BOT_TOKEN';
// When the bot is ready, log a message to the console
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
// When a user sends a message, check if they are authenticated
client.on('message', async (msg) => {
if (!msg.author.bot && !msg.author.authenticated) {
const filter = (m) => m.author.id === msg.author.id;
const collector = msg.channel.createMessageCollector(filter, { time: 15000 });
// Send an authentication message to the user
msg.author.send('Please authenticate yourself by clicking this link: ' + generateAuthURL(msg.author.id));
collector.on('collect', async (m) => {
// Check if the message contains the authentication code
if (m.content.startsWith('!auth ')) {
const code = m.content.slice(6);
const { access_token } = await getAccessToken(code);
// Set the user's authenticated status and access token
msg.author.authenticated = true;
msg.author.access_token = access_token;
collector.stop();
}
});
collector.on('end', () => {
if (!msg.author.authenticated) {
msg.author.send('Authentication timed out.');
}
});
}
});
// Generate an authentication URL for the user
function generateAuthURL(userId) {
const redirectURI = encodeURIComponent('YOUR_REDIRECT_URL');
const scopes = 'identify';
const clientID = 'YOUR_CLIENT_ID';
return `https://discord.com/api/oauth2/authorize?client_id=${clientID}&redirect_uri=${redirectURI}&response_type=code&scope=${scopes}&state=${userId}`;
}
// Exchange the authorization code for an access token
async function getAccessToken(code) {
const redirectURI = encodeURIComponent('YOUR_REDIRECT_URL');
const clientID = 'YOUR_CLIENT_ID';
const clientSecret = 'YOUR_CLIENT_SECRET';
const res = await fetch('https://discord.com/api/oauth2/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `grant_type=authorization_code&code=${code}&redirect_uri=${redirectURI}&client_id=${clientID}&client_secret=${clientSecret}`,
});
return await res.json();
}
client.login(token);

Longest Palindromic Substring

Nov 19, 2022CodeCatch

0 likes • 1 view

const longestPalindrome = (s) => {
if(s.length === 1) return s
const odd = longestOddPalindrome(s)
const even = longestEvenPalindrome(s)
if(odd.length >= even.length) return odd
if(even.length > odd.length) return even
};
const longestOddPalindrome = (s) => {
let longest = 0
let longestSubStr = ""
for(let i = 1; i < s.length; i++) {
let currentLongest = 1
let currentLongestSubStr = ""
let left = i - 1
let right = i + 1
while(left >= 0 && right < s.length) {
const leftLetter = s[left]
const rightLetter = s[right]
left--
right++
if(leftLetter === rightLetter) {
currentLongest += 2
currentLongestSubStr = s.slice(left+1, right)
} else break
}
if(currentLongest > longest) {
if(currentLongestSubStr) longestSubStr = currentLongestSubStr
else longestSubStr = s[i]
longest = currentLongest
}
}
return longestSubStr
}
const longestEvenPalindrome = (s) => {
let longest = 0
let longestSubStr = ""
for(let i = 0; i < s.length - 1; i++) {
if(s[i] !== s[i+1]) continue;
let currentLongest = 2
let currentLongestSubStr = ""
let left = i - 1
let right = i + 2
while(left >= 0 && right < s.length) {
const leftLetter = s[left]
const rightLetter = s[right]
left--
right++
if(leftLetter === rightLetter) {
currentLongest += 2
currentLongestSubStr = s.slice(left+1, right)
} else break
}
if(currentLongest > longest) {
if(currentLongestSubStr) longestSubStr = currentLongestSubStr
else longestSubStr = s[i] + s[i+1]
longest = currentLongest
}
}
return longestSubStr
}
console.log(longestPalindrome("babad"))

Subsets of an array

Nov 19, 2022CodeCatch

0 likes • 2 views

const getSubsets = arr => arr.reduce((prev, curr) => prev.concat(prev.map(k => k.concat(curr))), [[]]);
// Examples
getSubsets([1, 2]); // [[], [1], [2], [1, 2]]
getSubsets([1, 2, 3]); // [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

Heroku Production Build

Mar 11, 2021CHS

1 like • 1 view

if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}

Mongoose Model

Mar 11, 2021CHS

0 likes • 1 view

const mongoose = require('mongoose')
const UserSchema = new mongoose.Schema({
username: {
type: String,
required: true
},
email: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
})
module.exports = User = mongoose.model('user', UserSchema)

Zybooks?

Oct 29, 2020LeifMessinger

0 likes • 2 views

questions = Array.from(document.querySelectorAll(".multiple-choice-question"));
async function hackRadio(question){
if(question.querySelector(".question-chevron").getAttribute("aria-label") == "Question completed") return;
let answerChoices = question.querySelectorAll(".zb-radio-button");
async function guess(answerChoice){
answerChoice.querySelector("label").click();
}
let pause = 0;
for(let answerChoice of answerChoices){
setTimeout(()=>{guess(answerChoice)},pause); //No need to check given that it will record the correct answer anyways.
pause += 1000;
}
}
for(let question of questions){
hackRadio(question);
}
questions = Array.from(document.querySelectorAll(".short-answer-question"));
async function hackShortAnswer(question){
if(question.querySelector(".question-chevron").getAttribute("aria-label") == "Question completed") return;
question.querySelector("textarea").value = question.querySelector(".forfeit-answer").textContent;
//question.querySelector(".check-button").click(); They are smart bastards
}
for(let question of questions){
const showAnswerButton = question.querySelector(".show-answer-button");
showAnswerButton.click();
showAnswerButton.click();
hackShortAnswer(question);
}