Skip to main content

JWT Authentication

CHS
0 likes • Mar 11, 2021 • 0 views
JavaScript
Loading...

More JavaScript Posts

retryPromise.js

0 likes • Oct 20, 2023 • 12 views
JavaScript
//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)

MongoDB Connection

0 likes • Oct 15, 2022 • 4 views
JavaScript
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});

React - Lifting State

CHS
0 likes • Jan 25, 2023 • 2 views
JavaScript
export const Main = () => {
const [title, setTitle] = useState('');
return (
<ChildComponent
title={title}
onChange={e => setTitle(e.target.value)}
/>
);
};
export const ChildComponent = ({ title, onChange }) => {
return (
<Box component="form" onSubmit={() => {}} noValidate mt={5}>
<TextField
fullWidth
id="title"
label="Title"
name="title"
autoComplete="title"
autoFocus
color="primary"
variant="filled"
InputLabelProps={{ shrink: true }}
value={title}
onChange={onChange}
/>
</Box>
);
};

LeetCode Product Except Self

CHS
0 likes • Sep 13, 2023 • 6 views
JavaScript
/**
* @param {number[]} nums
* @return {number[]}
*/
var productExceptSelf = function(nums) {
var output = [];
var leftMult = 1;
var rightMult = 1;
for (var i=nums.length - 1; i >= 0; i--) {
output[i] = rightMult;
rightMult *= nums[i];
console.log({output: JSON.stringify(output), i})
}
for (var j=0; j < nums.length; j++) {
output[j] *= leftMult;
leftMult *= nums[j];
console.log({output: JSON.stringify(output), j})
}
return output;
};
console.log(productExceptSelf([1, 2, 3, 4]))

deep merge objects

0 likes • Nov 19, 2022 • 2 views
JavaScript
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 ] } }

copyString.js

0 likes • Nov 8, 2023 • 5 views
JavaScript
function copyString(text){
async function navigatorClipboardCopy(text){
if(document.location.protocol != "https:"){
return false;
}
return new Promise((resolve, reject)=>{
navigator.clipboard.writeText(text).then(()=>{resolve(true);}, ()=>{resolve(false);});
});
}
function domCopy(text){
if(!(document.execCommand)){
console.warn("They finally deprecated document.execCommand!");
}
const input = document.createElement('textarea');
input.value = text;
document.body.appendChild(input);
input.select();
const success = document.execCommand('copy');
document.body.removeChild(input);
return success;
}
function promptCopy(){
prompt("Copy failed. Might have ... somewhere. Check console.", text);
console.log(text);
}
function done(){
alert("Copied to clipboard");
}
navigatorClipboardCopy(text).catch(()=>{return false;}).then((success)=>{
if(success){
done();
}else{
if(domCopy(text)){
done();
}else{
promptCopy();
}
}
});
}