Skip to main content

MongoDB Connection

Oct 15, 2022CodeCatch
Loading...

More JavaScript Posts

linear search

Nov 19, 2022CodeCatch

0 likes • 0 views

const linearSearch = (arr, item) => {
for (const i in arr) {
if (arr[i] === item) return +i;
}
return -1;
};
linearSearch([2, 9, 9], 9); // 1
linearSearch([2, 9, 9], 7); // -1

typewriter-effect in Vanilla JS and React

Jan 25, 2023CHS

0 likes • 7 views

// Vanilla JS Solution:
var app = document.getElementById('app');
var typewriter = new Typewriter(app, { loop: true });
typewriter
.typeString("I'm John and I'm a super cool web developer")
.pauseFor(3000)
.deleteChars(13) // "web developer" = 13 characters
.typeString("person to talk with!") // Will display "I'm John and I'm a super cool person to talk with!"
.start();
// React Solution:
import Typewriter from 'typewriter-effect';
<Typewriter
options={{ loop: true }}
onInit={typewriter => {
typewriter
.typeString("I'm John and I'm a super cool web developer")
.pauseFor(3000)
.deleteChars(13) // "web developer" = 13 characters
.typeString("person to talk with!") // Will display "I'm John and I'm a super cool person to talk with!"
.start();
}}
/>

binary search

Nov 19, 2022CodeCatch

0 likes • 1 view

const binarySearch = (arr, item) => {
let l = 0,
r = arr.length - 1;
while (l <= r) {
const mid = Math.floor((l + r) / 2);
const guess = arr[mid];
if (guess === item) return mid;
if (guess > item) r = mid - 1;
else l = mid + 1;
}
return -1;
};
binarySearch([1, 2, 3, 4, 5], 1); // 0
binarySearch([1, 2, 3, 4, 5], 5); // 4
binarySearch([1, 2, 3, 4, 5], 6); // -1

retryPromise.js

Oct 20, 2023LeifMessinger

0 likes • 14 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)

Longest Palindromic Substring

Nov 19, 2022CodeCatch

0 likes • 1 view

const longestPalindrome = (s) => {
if(s.length === 1) return s
const odd = longestOddPalindrome(s)
const even = longestEvenPalindrome(s)
if(odd.length >= even.length) return odd
if(even.length > odd.length) return even
};
const longestOddPalindrome = (s) => {
let longest = 0
let longestSubStr = ""
for(let i = 1; i < s.length; i++) {
let currentLongest = 1
let currentLongestSubStr = ""
let left = i - 1
let right = i + 1
while(left >= 0 && right < s.length) {
const leftLetter = s[left]
const rightLetter = s[right]
left--
right++
if(leftLetter === rightLetter) {
currentLongest += 2
currentLongestSubStr = s.slice(left+1, right)
} else break
}
if(currentLongest > longest) {
if(currentLongestSubStr) longestSubStr = currentLongestSubStr
else longestSubStr = s[i]
longest = currentLongest
}
}
return longestSubStr
}
const longestEvenPalindrome = (s) => {
let longest = 0
let longestSubStr = ""
for(let i = 0; i < s.length - 1; i++) {
if(s[i] !== s[i+1]) continue;
let currentLongest = 2
let currentLongestSubStr = ""
let left = i - 1
let right = i + 2
while(left >= 0 && right < s.length) {
const leftLetter = s[left]
const rightLetter = s[right]
left--
right++
if(leftLetter === rightLetter) {
currentLongest += 2
currentLongestSubStr = s.slice(left+1, right)
} else break
}
if(currentLongest > longest) {
if(currentLongestSubStr) longestSubStr = currentLongestSubStr
else longestSubStr = s[i] + s[i+1]
longest = currentLongest
}
}
return longestSubStr
}
console.log(longestPalindrome("babad"))

heap sort

Nov 19, 2022CodeCatch

0 likes • 0 views

const heapsort = arr => {
const a = [...arr];
let l = a.length;
const heapify = (a, i) => {
const left = 2 * i + 1;
const right = 2 * i + 2;
let max = i;
if (left < l && a[left] > a[max]) max = left;
if (right < l && a[right] > a[max]) max = right;
if (max !== i) {
[a[max], a[i]] = [a[i], a[max]];
heapify(a, max);
}
};
for (let i = Math.floor(l / 2); i >= 0; i -= 1) heapify(a, i);
for (i = a.length - 1; i > 0; i--) {
[a[0], a[i]] = [a[i], a[0]];
l--;
heapify(a, 0);
}
return a;
};
heapsort([6, 3, 4, 1]); // [1, 3, 4, 6]