Skip to main content

linear search

Nov 19, 2022CodeCatch
Loading...

More JavaScript Posts

luhnCheck implementation

Nov 19, 2022CodeCatch

0 likes • 1 view

const luhnCheck = num => {
let arr = (num + '')
.split('')
.reverse()
.map(x => parseInt(x));
let lastDigit = arr.splice(0, 1)[0];
let sum = arr.reduce(
(acc, val, i) => (i % 2 !== 0 ? acc + val : acc + ((val *= 2) > 9 ? val - 9 : val)),
0
);
sum += lastDigit;
return sum % 10 === 0;
};
luhnCheck('4485275742308327'); // true
luhnCheck(6011329933655299); // true
luhnCheck(123456789); // false

geometric progression

Nov 19, 2022CodeCatch

0 likes • 0 views

const geometricProgression = (end, start = 1, step = 2) =>
Array.from({
length: Math.floor(Math.log(end / start) / Math.log(step)) + 1,
}).map((_, i) => start * step ** i);
geometricProgression(256); // [1, 2, 4, 8, 16, 32, 64, 128, 256]
geometricProgression(256, 3); // [3, 6, 12, 24, 48, 96, 192]
geometricProgression(256, 1, 4); // [1, 4, 16, 64, 256]

graph example

Nov 19, 2022CodeCatch

0 likes • 0 views

class Graph {
constructor(directed = true) {
this.directed = directed;
this.nodes = [];
this.edges = new Map();
}
addNode(key, value = key) {
this.nodes.push({ key, value });
}
addEdge(a, b, weight) {
this.edges.set(JSON.stringify([a, b]), { a, b, weight });
if (!this.directed)
this.edges.set(JSON.stringify([b, a]), { a: b, b: a, weight });
}
removeNode(key) {
this.nodes = this.nodes.filter(n => n.key !== key);
[...this.edges.values()].forEach(({ a, b }) => {
if (a === key || b === key) this.edges.delete(JSON.stringify([a, b]));
});
}
removeEdge(a, b) {
this.edges.delete(JSON.stringify([a, b]));
if (!this.directed) this.edges.delete(JSON.stringify([b, a]));
}
findNode(key) {
return this.nodes.find(x => x.key === key);
}
hasEdge(a, b) {
return this.edges.has(JSON.stringify([a, b]));
}
setEdgeWeight(a, b, weight) {
this.edges.set(JSON.stringify([a, b]), { a, b, weight });
if (!this.directed)
this.edges.set(JSON.stringify([b, a]), { a: b, b: a, weight });
}
getEdgeWeight(a, b) {
return this.edges.get(JSON.stringify([a, b])).weight;
}
adjacent(key) {
return [...this.edges.values()].reduce((acc, { a, b }) => {
if (a === key) acc.push(b);
return acc;
}, []);
}
indegree(key) {
return [...this.edges.values()].reduce((acc, { a, b }) => {
if (b === key) acc++;
return acc;
}, 0);
}
outdegree(key) {
return [...this.edges.values()].reduce((acc, { a, b }) => {
if (a === key) acc++;
return acc;
}, 0);
}
}
const g = new Graph();
g.addNode('a');
g.addNode('b');
g.addNode('c');
g.addNode('d');
g.addEdge('a', 'c');
g.addEdge('b', 'c');
g.addEdge('c', 'b');
g.addEdge('d', 'a');
g.nodes.map(x => x.value); // ['a', 'b', 'c', 'd']
[...g.edges.values()].map(({ a, b }) => `${a} => ${b}`);
// ['a => c', 'b => c', 'c => b', 'd => a']
g.adjacent('c'); // ['b']
g.indegree('c'); // 2
g.outdegree('c'); // 1
g.hasEdge('d', 'a'); // true
g.hasEdge('a', 'd'); // false
g.removeEdge('c', 'b');
[...g.edges.values()].map(({ a, b }) => `${a} => ${b}`);
// ['a => c', 'b => c', 'd => a']
g.removeNode('c');
g.nodes.map(x => x.value); // ['a', 'b', 'd']
[...g.edges.values()].map(({ a, b }) => `${a} => ${b}`);
// ['d => a']
g.setEdgeWeight('d', 'a', 5);
g.getEdgeWeight('d', 'a'); // 5

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)

Timer

Feb 5, 2021LeifMessinger

0 likes • 2 views

class Timer{
start(){
this.startTime = Date.now();
}
stop(){
const dt = Date.now() - this.startTime;
console.log(dt);
return dt;
}
getExecTime(fun, asynchronous){
return asynchronous ? this.getAsyncExecTime(fun) : this.getSyncExecTime(fun);
}
getSyncExecTime(fun){
this.start();
fun();
return this.stop();
}
async getAsyncExecTime(fun){
this.start();
await fun();
return this.stop();
}
static average(fun, numTimes, asynchronous = false){
const times = [];
const promises = [];
let timer = new Timer();
if(asynchronous){
for(let i = 0; i < numTimes; i++){
timer.getAsyncExecTime(fun);
}
}else{
for(let i = 0; i < numTimes; i++){
timer.getSyncExecTime(fun);
}
}
return (times => times.reduce(((sum, acc) => sume + acc), 0) / times.length);
}
static async timeAsync(fun, numTimes){
if(numTimes <= 1) return new Timer().getAsyncExecTime(fun);
const promises = [];
let timer = new Timer(true);
for(let i = 0; i < numTimes; i++){
promises.push(fun().catch((e)=>{}));
}
try{
await Promise.all(promises).catch((e)=>{});
}catch(e){
//do absolutely nothing
}
return timer.stop();
}
constructor(start = false){
if(start) this.start();
}
}

Send mail with nodemailer

Nov 18, 2022AustinLeath

0 likes • 1 view

"use strict";
const nodemailer = require("nodemailer");
// async..await is not allowed in global scope, must use a wrapper
async function main() {
// Generate test SMTP service account from ethereal.email
// Only needed if you don't have a real mail account for testing
let testAccount = await nodemailer.createTestAccount();
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: "smtp.ethereal.email",
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: testAccount.user, // generated ethereal user
pass: testAccount.pass, // generated ethereal password
},
});
// send mail with defined transport object
let info = await transporter.sendMail({
from: '"Fred Foo 👻" <[email protected]>', // sender address
to: "[email protected], [email protected]", // list of receivers
subject: "Hello ✔", // Subject line
text: "Hello world?", // plain text body
html: "<b>Hello world?</b>", // html body
});
console.log("Message sent: %s", info.messageId);
// Message sent: <[email protected]>
// Preview only available when sending through an Ethereal account
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}
main().catch(console.error);