Skip to main content

Reverse a string

Nov 19, 2022CodeCatch
Loading...

More JavaScript Posts

Generate a random HEX color

Nov 18, 2022AustinLeath

0 likes • 1 view

// Or
const randomColor = () => `#${(~~(Math.random()*(1<<24))).toString(16)}`;
console.log(randomColor);

Function promisification

Nov 19, 2022CodeCatch

0 likes • 0 views

// promisify(f, true) to get array of results
function promisify(f, manyArgs = false) {
return function (...args) {
return new Promise((resolve, reject) => {
function callback(err, ...results) { // our custom callback for f
if (err) {
reject(err);
} else {
// resolve with all callback results if manyArgs is specified
resolve(manyArgs ? results : results[0]);
}
}
args.push(callback);
f.call(this, ...args);
});
};
}
// usage:
f = promisify(f, true);
f(...).then(arrayOfResults => ..., err => ...);

Truncate to fixed decimal

Nov 19, 2022CodeCatch

0 likes • 0 views

const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
// Examples
toFixed(25.198726354, 1); // 25.1
toFixed(25.198726354, 2); // 25.19
toFixed(25.198726354, 3); // 25.198
toFixed(25.198726354, 4); // 25.1987
toFixed(25.198726354, 5); // 25.19872
toFixed(25.198726354, 6); // 25.198726

Mee6 Spam Calculator

Mar 10, 2022LeifMessinger

0 likes • 1 view

//Use at https://mee6.xyz/leaderboard/732262089447702588
//Higher the spammy stat, the more spammy that person is.
//This is because mee doesn't give experience to people who post more comments in a minute.
function statBlock(title, value){
let elm = document.createElement("div");
elm.className = "leaderboardPlayerStatBlock";
let titleElm = document.createElement("div");
titleElm.className = "leaderboardPlayerStatName";
titleElm.textContent = title;
let valueElm = document.createElement("div");
valueElm.className = "leaderboardPlayerStatValue";
valueElm.textContent = value;
elm.appendChild(titleElm);
elm.appendChild(valueElm);
elm.remove = function(){
this.parentElement.removeChild(this);
}
return elm;
}
for(let player of Array.from(document.getElementsByClassName("leaderboardPlayer"))){
if(player.spamminess) player.spamminess.remove();
let messages = null;
let experience = null;
const statBlockArray = Array.from(player.querySelectorAll(".leaderboardPlayerStatBlock"));
for(let statBlock of statBlockArray){
const statName = statBlock.querySelector(".leaderboardPlayerStatName").textContent;
const text = statBlock.querySelector(".leaderboardPlayerStatValue").textContent;
const number = ((text.includes("k"))? (text.replace("k","") * 1000.0) : +(text));
if(statName.includes("MESSAGES")){
messages = number;
}else if(statName.includes("EXPERIENCE")){
experience = number;
}
}
const stats = player.querySelector(".leaderboardPlayerStats");
const messagesElement = stats.firstChild;
const spamminess = ((messages/experience)*2000.0).toFixed(2);
player.spamminess = stats.insertBefore(statBlock("SPAMMINESS", spamminess), messagesElement);
}

retryPromise.js

Oct 20, 2023LeifMessinger

0 likes • 18 views

//Retries maxRetries number of times, meaning that if you have 0, then it'll run the function once.
async function retryPromise(promiseFn, maxRetries = 3, delayOffset = 0, delayRandomRange = 0) {
return new Promise((resolve, reject) => {
promiseFn()
.then(resolve, (error) => { //On error
if (maxRetries <= 0) {
return reject(error);
} else {
if(delayRandomRange * Math.random() + delayOffset < 1.0){
return retryPromise(promiseFn, maxRetries - 1, delayOffset, delayRandomRange).then(resolve, reject);
}else{
return new Promise((resolveTwo, rejectTwo) => {
setTimeout(() => {
return retryPromise(promiseFn, maxRetries - 1, delayOffset, delayRandomRange).then(resolveTwo, rejectTwo);
}, delayRandomRange * Math.random() + delayOffset);
}).then(resolve, reject);
}
}
});
});
}
//Tests for that function.
//Returns a function that will fail numTimes times, then will return aValue
function functionThatReturnsAFunctionThatFailsACoupleTimes(numTimes, aValue){
return async function(){
if(numTimes == 0){
return aValue;
}
numTimes--;
throw false;
};
}
const SMALL_NUMBER = 10;
function testTest(failNumberOfTimes){
let functionThatFailsACoupleTimes = functionThatReturnsAFunctionThatFailsACoupleTimes(failNumberOfTimes, true);
//Test my test
for(let i = 0; i < (failNumberOfTimes * 2); ++i){
function evalTest(val){
let testTestFailedReason = "";
if(val === undefined){
testTestFailedReason = "Test test returned undefined for some reason.";
}
if((i + 1) > failNumberOfTimes){
if(val === true){
//We're good
}else{
testTestFailedReason = "Test test didn't return true when it should have.";
}
}else{
if(val === false){
//We're good
}else{
testTestFailedReason = "Test test didn't return false when it should have.";
}
}
testTestFailedReason = testTestFailedReason || "Test test passed test case";
console.log(testTestFailedReason, "at index", i, "where the function returned", val);
}
functionThatFailsACoupleTimes().then(evalTest, evalTest)
};
}
testTest(SMALL_NUMBER);
let testCaseCounter = 1;
const throwsNoError = [
(val)=>{
if(val == true){
console.log("Passed test case " + (testCaseCounter++));
}else{
console.error("Unexpected return value", val);
}
},
()=>{
console.error("It wasn't supposed to fail!")
}
]
const throwsError = [
(val)=>{
console.error("It wasn't supposed to succeed!", val);
},
(val)=>{
if(val == false){
console.log("Passed test case " + (testCaseCounter++));
}else{
console.error("Unexpected return value", val);
}
}
];
//Runs SMALL_NUMBER times, because SMALL_NUMBER - 1 is the number of retries after the first one
let functionThatFailsACoupleTimes = functionThatReturnsAFunctionThatFailsACoupleTimes(SMALL_NUMBER - 1, true);
retryPromise(functionThatFailsACoupleTimes, SMALL_NUMBER - 1).then(...throwsNoError)
functionThatFailsACoupleTimes = functionThatReturnsAFunctionThatFailsACoupleTimes(SMALL_NUMBER - 1, true);
//Runs SMALL_NUMBER - 1 times, because SMALL_NUMBER - 2 is the number of retries after the first one
retryPromise(functionThatFailsACoupleTimes, SMALL_NUMBER - 2).then(...throwsError)
//Testing the delay. You'll have to wait a bit too.
functionThatFailsACoupleTimes = functionThatReturnsAFunctionThatFailsACoupleTimes(SMALL_NUMBER - 1, true);
//Runs SMALL_NUMBER times, because SMALL_NUMBER - 1 is the number of retries after the first one
retryPromise(functionThatFailsACoupleTimes, SMALL_NUMBER - 1, 500, 500).then(...throwsNoError)
functionThatFailsACoupleTimes = functionThatReturnsAFunctionThatFailsACoupleTimes(SMALL_NUMBER - 1, true);
//Runs SMALL_NUMBER - 1 times, because SMALL_NUMBER - 2 is the number of retries after the first one
retryPromise(functionThatFailsACoupleTimes, SMALL_NUMBER - 2, 500, 500).then(...throwsError)

LeetCode Contains Duplicate

Sep 13, 2023C S

0 likes • 2 views

/**
* @param {number[]} nums
* @return {boolean}
*/
var containsDuplicate = function(nums) {
return new Set(nums).size !== nums.length
};