Loading...
More JavaScript Posts
class TreeNode {constructor(key, value = key, parent = null) {this.key = key;this.value = value;this.parent = parent;this.children = [];}get isLeaf() {return this.children.length === 0;}get hasChildren() {return !this.isLeaf;}}class Tree {constructor(key, value = key) {this.root = new TreeNode(key, value);}*preOrderTraversal(node = this.root) {yield node;if (node.children.length) {for (let child of node.children) {yield* this.preOrderTraversal(child);}}}*postOrderTraversal(node = this.root) {if (node.children.length) {for (let child of node.children) {yield* this.postOrderTraversal(child);}}yield node;}insert(parentNodeKey, key, value = key) {for (let node of this.preOrderTraversal()) {if (node.key === parentNodeKey) {node.children.push(new TreeNode(key, value, node));return true;}}return false;}remove(key) {for (let node of this.preOrderTraversal()) {const filtered = node.children.filter(c => c.key !== key);if (filtered.length !== node.children.length) {node.children = filtered;return true;}}return false;}find(key) {for (let node of this.preOrderTraversal()) {if (node.key === key) return node;}return undefined;}}const tree = new Tree(1, 'AB');tree.insert(1, 11, 'AC');tree.insert(1, 12, 'BC');tree.insert(12, 121, 'BG');[...tree.preOrderTraversal()].map(x => x.value);// ['AB', 'AC', 'BC', 'BCG']tree.root.value; // 'AB'tree.root.hasChildren; // truetree.find(12).isLeaf; // falsetree.find(121).isLeaf; // truetree.find(121).parent.value; // 'BC'tree.remove(12);[...tree.postOrderTraversal()].map(x => x.value);// ['AC', 'AB']
//Upvotes comments according to a regex pattern. I tried it out on https://www.reddit.com/r/VALORANT/comments/ne74n4/please_admire_this_clip_precise_gunplay_btw///Known bugs://If a comment was already upvoted, it gets downvoted//For some reason, it has around a 50-70% success rate. The case insensitive bit works, but I think some of the query selector stuff gets changed. Still, 50% is goodlet comments = document.getElementsByClassName("_3tw__eCCe7j-epNCKGXUKk"); //Comment classlet commentsToUpvote = [];const regexToMatch = /wtf/gi;for(let comment of comments){let text = comment.querySelector("._1qeIAgB0cPwnLhDF9XSiJM"); //Comment content classif(text == undefined){continue;}text = text.textContent;if(regexToMatch.test(text)){console.log(text);commentsToUpvote.push(comment);}}function upvote(comment){console.log(comment.querySelector(".icon-upvote")); //Just showing you what it's doingcomment.querySelector(".icon-upvote").click();}function slowRecurse(){let comment = commentsToUpvote.pop(); //It's gonna go bottom to top but whateverif(comment != undefined){upvote(comment);setTimeout(slowRecurse,500);}}slowRecurse();
const deepMerge = (a, b, fn) =>[...new Set([...Object.keys(a), ...Object.keys(b)])].reduce((acc, key) => ({ ...acc, [key]: fn(key, a[key], b[key]) }),{});deepMerge({ a: true, b: { c: [1, 2, 3] } },{ a: false, b: { d: [1, 2, 3] } },(key, a, b) => (key === 'a' ? a && b : Object.assign({}, a, b)));// { a: false, b: { c: [ 1, 2, 3 ], d: [ 1, 2, 3 ] } }
var d = new Date();var d = new Date(milliseconds);var d = new Date(dateString);var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
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 consoleclient.on('ready', () => {console.log(`Logged in as ${client.user.tag}!`);});// When a user sends a message, check if they are authenticatedclient.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 usermsg.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 codeif (m.content.startsWith('!auth ')) {const code = m.content.slice(6);const { access_token } = await getAccessToken(code);// Set the user's authenticated status and access tokenmsg.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 userfunction 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 tokenasync 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);
const formatDuration = ms => {if (ms < 0) ms = -ms;const time = {day: Math.floor(ms / 86400000),hour: Math.floor(ms / 3600000) % 24,minute: Math.floor(ms / 60000) % 60,second: Math.floor(ms / 1000) % 60,millisecond: Math.floor(ms) % 1000};return Object.entries(time).filter(val => val[1] !== 0).map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`).join(', ');};formatDuration(1001); // '1 second, 1 millisecond'formatDuration(34325055574); // '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'