Skip to main content

Monotonic Array

0 likes • Nov 19, 2022 • 2 views
JavaScript
Loading...

More JavaScript Posts

quick sort

0 likes • Nov 19, 2022 • 0 views
JavaScript
const quickSort = arr => {
const a = [...arr];
if (a.length < 2) return a;
const pivotIndex = Math.floor(arr.length / 2);
const pivot = a[pivotIndex];
const [lo, hi] = a.reduce(
(acc, val, i) => {
if (val < pivot || (val === pivot && i != pivotIndex)) {
acc[0].push(val);
} else if (val > pivot) {
acc[1].push(val);
}
return acc;
},
[[], []]
);
return [...quickSort(lo), pivot, ...quickSort(hi)];
};
quickSort([1, 6, 1, 5, 3, 2, 1, 4]); // [1, 1, 1, 2, 3, 4, 5, 6]

Simple Express Server

0 likes • Oct 15, 2022 • 66 views
JavaScript
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})

Authenticate Discord User

0 likes • Mar 28, 2023 • 1 view
JavaScript
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);

permutations

0 likes • Nov 19, 2022 • 0 views
JavaScript
const permutations = arr => {
if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;
return arr.reduce(
(acc, item, i) =>
acc.concat(
permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [
item,
...val,
])
),
[]
);
};
permutations([1, 33, 5]);
// [ [1, 33, 5], [1, 5, 33], [33, 1, 5], [33, 5, 1], [5, 1, 33], [5, 33, 1] ]

ESPN Web Scrape

0 likes • Oct 15, 2023 • 6 views
JavaScript
//Disclaimer: I do not condone mass web scraping of ESPN websites, and this is just theoretical code that hasn't been used.
//Scrape player stats off of https://www.espn.com/nfl/team/roster/_/name/phi/philadelphia-eagles
//Example player JS object
/*
{
"shortName": "S. Opeta",
"name": "Sua Opeta",
"href": "http://www.espn.com/nfl/player/_/id/3121009/sua-opeta",
"uid": "s:20~l:28~a:3121009",
"guid": "dec19157-e984-f981-3724-498281328c97",
"id": "3121009",
"height": "6' 4\"",
"weight": "305 lbs",
"age": 27,
"position": "G",
"jersey": "78",
"birthDate": "08/15/96",
"headshot": "https://a.espncdn.com/i/headshots/nfl/players/full/3121009.png",
"lastName": "Sua Opeta",
"experience": 4,
"college": "Weber State"
}
*/
//The page needs to be focused, so you have to put this code in a bookmarklet and click the page before clicking it. Allegedly.
navigator.clipboard.writeText(JSON.stringify(
window["__espnfitt__"].page.content.roster.groups.flatMap((group)=>{
return group.athletes.map((athlete)=>{
//We can assume all football players are above 100 lbs and below 1000 lbs.
athlete.weight = parseInt(athlete.weight.substring(0,3));
if(athlete.experience == "R") athlete.experience = 0;
else athlete.experience = parseInt(athlete.experience);
//We can assume players are at least 1 foot, or under 10 feet tall.
athlete.inches = 12 * parseInt(athlete.height.substring(0, 1)); //Add feet in inches
athlete.inches += parseInt(athlete.height.substring(2).replaceAll("\"", "").trim()); //Add remaining inches
const monthDayYear = athlete.birthDate.split("/");
athlete.birthMonth = parseInt(monthDayYear[0]);
athlete.birthDay = parseInt(monthDayYear[1]);
athlete.birthYear = parseInt(monthDayYear[2]);
//The only really useful stuff we get from this is Height, weight, left handedness, age, position, and birthday
return athlete;
});
})
, null, "\t")).then(null, ()=>{alert("That failed.")});
//Changes all the team links on this page https://www.espn.com/nfl/stats/team to the team's roster for easier scraping
$$("table > tbody > tr > td > div > div > a").forEach((elm)=>{
elm.setAttribute("href", elm.getAttribute("href").replace("team/", "team/roster/"));
});

UNT canvas file finder utility

0 likes • Nov 18, 2022 • 0 views
JavaScript
//use this with canvas file finder
function NewTab(testing) {
window.open(testing, "_blank");
}
for(test in results) {
var testing = 'https://unt.instructure.com/files/' + test + '/download';
NewTab(testing);
}