Skip to main content

Get union of arrays

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

More JavaScript Posts

Reverse a string in Java

0 likes • Nov 20, 2022 • 1 view
JavaScript
new StringBuilder(hi).reverse().toString()

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);

arithmetic progression

0 likes • Nov 19, 2022 • 0 views
JavaScript
const arithmeticProgression = (n, lim) =>
Array.from({ length: Math.ceil(lim / n) }, (_, i) => (i + 1) * n );
arithmeticProgression(5, 25); // [5, 10, 15, 20, 25]

unzipWith() function

0 likes • Nov 19, 2022 • 0 views
JavaScript
const unzipWith = (arr, fn) =>
arr
.reduce(
(acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc),
Array.from({
length: Math.max(...arr.map(x => x.length))
}).map(x => [])
)
.map(val => fn(...val));
unzipWith(
[
[1, 10, 100],
[2, 20, 200],
],
(...args) => args.reduce((acc, v) => acc + v, 0)
);
// [3, 30, 300]

K-means clustering

0 likes • Nov 19, 2022 • 0 views
JavaScript
const kMeans = (data, k = 1) => {
const centroids = data.slice(0, k);
const distances = Array.from({ length: data.length }, () =>
Array.from({ length: k }, () => 0)
);
const classes = Array.from({ length: data.length }, () => -1);
let itr = true;
while (itr) {
itr = false;
for (let d in data) {
for (let c = 0; c < k; c++) {
distances[d][c] = Math.hypot(
...Object.keys(data[0]).map(key => data[d][key] - centroids[c][key])
);
}
const m = distances[d].indexOf(Math.min(...distances[d]));
if (classes[d] !== m) itr = true;
classes[d] = m;
}
for (let c = 0; c < k; c++) {
centroids[c] = Array.from({ length: data[0].length }, () => 0);
const size = data.reduce((acc, _, d) => {
if (classes[d] === c) {
acc++;
for (let i in data[0]) centroids[c][i] += data[d][i];
}
return acc;
}, 0);
for (let i in data[0]) {
centroids[c][i] = parseFloat(Number(centroids[c][i] / size).toFixed(2));
}
}
}
return classes;
};
kMeans([[0, 0], [0, 1], [1, 3], [2, 0]], 2); // [0, 1, 1, 0]

Monotonic Array

0 likes • Nov 19, 2022 • 2 views
JavaScript
// Time Complexity : O(N)
// Space Complexity : O(1)
var isMonotonic = function(nums) {
let isMono = null;
for(let i = 1; i < nums.length; i++) {
if(isMono === null) {
if(nums[i - 1] < nums[i]) isMono = 0;
else if(nums[i - 1] > nums[i]) isMono = 1;
continue;
}
if(nums[i - 1] < nums[i] && isMono !== 0) {
return false;
}
else if(nums[i - 1] > nums[i] && isMono !== 1) {
return false;
}
}
return true;
};
let nums1 = [1,2,2,3]
let nums2 = [6,5,4,4]
let nums3 = [1,3,2]
console.log(isMonotonic(nums1));
console.log(isMonotonic(nums2));
console.log(isMonotonic(nums3));