• Nov 19, 2022 •CodeCatch
0 likes • 0 views
const primes = num => { let arr = Array.from({ length: num - 1 }).map((x, i) => i + 2), sqroot = Math.floor(Math.sqrt(num)), numsTillSqroot = Array.from({ length: sqroot - 1 }).map((x, i) => i + 2); numsTillSqroot.forEach(x => (arr = arr.filter(y => y % x !== 0 || y === x))); return arr; }; primes(10); // [2, 3, 5, 7]
• Mar 28, 2023 •Helper
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);
• Mar 11, 2021 •C S
0 likes • 6 views
router.post("/", async (req, res) => { const { email, password } = req.body; try { if (!email) return res.status(400).json({ msg: "An email is required" }); if (!password) return res.status(400).json({ msg: "A password is required" }); const user = await User.findOne({ email }).select("_id password"); if (!user) return res.status(400).json({ msg: "Invalid credentials" }); const match = await bcrypt.compare(password, user.password); if (!match) return res.status(400).json({ msg: "Invalid credentials" }); const accessToken = genAccessToken({ id: user._id }); const refreshToken = genRefreshToken({ id: user._id }); res.cookie("token", refreshToken, { expires: new Date(Date.now() + 604800), httpOnly: true, }); res.json({ accessToken }); } catch (err) { console.log(err.message); res.status(500).json({ msg: "Error logging in user" }); } });
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; // true tree.find(12).isLeaf; // false tree.find(121).isLeaf; // true tree.find(121).parent.value; // 'BC' tree.remove(12); [...tree.postOrderTraversal()].map(x => x.value); // ['AC', 'AB']
• Jan 26, 2023 •AustinLeath
0 likes • 5 views
function printHeap(heap, index, level) { if (index >= heap.length) { return; } console.log(" ".repeat(level) + heap[index]); printHeap(heap, 2 * index + 1, level + 1); printHeap(heap, 2 * index + 2, level + 1); } //You can call this function by passing in the heap array and the index of the root node, which is typically 0, and level = 0. let heap = [3, 8, 7, 15, 17, 30, 35, 2, 4, 5, 9]; printHeap(heap,0,0)
0 likes • 2 views
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32; const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9; // Examples celsiusToFahrenheit(15); // 59 celsiusToFahrenheit(0); // 32 celsiusToFahrenheit(-20); // -4 fahrenheitToCelsius(59); // 15 fahrenheitToCelsius(32); // 0