Skip to main content

URL Search Term Generator

Jan 17, 2021C S
Loading...

More JavaScript Posts

JS Test

Mar 9, 2021LeifMessinger

0 likes • 1 view

alert("bruh")

levenshtein distance

Nov 19, 2022CodeCatch

0 likes • 1 view

const levenshteinDistance = (s, t) => {
if (!s.length) return t.length;
if (!t.length) return s.length;
const arr = [];
for (let i = 0; i <= t.length; i++) {
arr[i] = [i];
for (let j = 1; j <= s.length; j++) {
arr[i][j] =
i === 0
? j
: Math.min(
arr[i - 1][j] + 1,
arr[i][j - 1] + 1,
arr[i - 1][j - 1] + (s[j - 1] === t[i - 1] ? 0 : 1)
);
}
}
return arr[t.length][s.length];
};
levenshteinDistance('duck', 'dark'); // 2

drag and drop uploader

Nov 18, 2022AustinLeath

0 likes • 0 views

const dragAndDropDiv = editor.container;
dragAndDropDiv.addEventListener('dragover', function(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
});
dragAndDropDiv.addEventListener("drop",function(e){
// Prevent default behavior (Prevent file from being opened)
e.stopPropagation();
e.preventDefault();
const files = e.dataTransfer.items; // Array of all files
console.assert(files.length >= 1);
if (files[0].kind === 'file') {
var file = e.dataTransfer.items[0].getAsFile();
const fileSize = file.size;
const fileName = file.name;
const fileMimeType = file.type;
reader = new FileReader();
reader.onloadend = function(){
editor.setValue(reader.result);
}
reader.readAsText(file);
}else{
//Maybe handle if text is dropped
console.log(files[0].kind);
}
});

Horizontal legend (d3.js)

Dec 17, 2024shaiRos

0 likes • 2 views

const rectSize = 15; // Size of the color box
const spacing = 5; // Space between legend items
let legend = canvas.append('g').attr('class','chart-legend')
.attr('transform', `translate(${0}, ${height + 3})`);
// Sample data for the legend
const legendData = [
{ label: 'low', color: '#1f77b4' },
{ label: 'medium', color: '#ff7f0e' },
{ label: 'high', color: '#2ca02c' },
{ label: 'very high', color: '#2ca02c' }
];
legend.selectAll('g')
.data(legendData)
.join('g')
.attr('class', 'legend-item')
.each(function (d, i) {
const legendItem = d3.select(this);
console.log(d.label)
console.log(d.label?.length)
let labelWidth = (d.label.length * 5) + 7 + 15
var bbox = legendItem.node().getBBox()
var width = bbox.width
console.log(width)
// Add rectangle for color
legendItem.append('rect')
.attr('width', rectSize)
.attr('height', rectSize)
.attr('fill', d.color);
// Add label
legendItem.append('text')
.attr('x', rectSize + spacing) // Position text to the right of the rectangle
.attr('y', rectSize / 2) // Align text vertically with the rectangle
.attr('dy', '.35em') // Adjust vertical alignment
.attr('text-anchor', 'start') // Align text to the start
.text(d.label)
.attr('fill', 'black'); // Optional: Text color
// legendItem.attr('transform', `translate(${i * (rectSize + spacing + labelWidth)}, 0)`) // Position each item horizontally
});
const legendItems_spacing = 12
var legendLength = 0
legend.selectAll('.legend-item').each(function(d,i) {
d3.select(this).attr('transform',function() {
var bbox = d3.select(this).node().getBBox()
var width = bbox.width
// if (width == 0) width = (d.text.length * 5) +15 // not in dom yet
let startingPosition = 0
if (i > 0) {
startingPosition = legendLength
}
legendLength += width + legendItems_spacing
// return `translate(${xx - (width + 30)},0$)`
return `translate(${startingPosition},0)`
})
})

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

Composing components

Nov 19, 2022CodeCatch

0 likes • 0 views

function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);