Created
April 6, 2022 03:24
-
-
Save roryabraham/8e0d32187170ac221fe2e438956e6ddf to your computer and use it in GitHub Desktop.
JavaScript utility for generating random stuff and doing stuff randomly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {promiseWhile} from './promiseWhile'; | |
/** | |
* Flip a coin! | |
* | |
* @returns {Boolean} | |
*/ | |
function randomBool() { | |
return Math.random() < 0.5; | |
} | |
/** | |
* Generate a random number between min and max, inclusive | |
* | |
* @param {Number} min | |
* @param {Number} max | |
* @returns {Number} | |
*/ | |
function randomInt(min, max) { | |
return (Math.floor(Math.random() * (max - min))) + min; | |
} | |
/** | |
* Repeatedly execute a function at random intervals. | |
* | |
* @param {Function} func – the function to execute | |
* @param {Number} min – the minimum time to sleep between executions of the function | |
* @param {Number} max – the maximum time to sleep between executions of the function | |
* @returns {Function} – a cleanup function to stop executing the function at random intervals | |
*/ | |
function execAtRandomIntervals(func, min, max) { | |
let shouldContinue = true; | |
promiseWhile( | |
() => shouldContinue, | |
() => new Promise((resolve) => { | |
const sleep = randomInt(min, max); | |
setTimeout(() => { | |
func(); | |
resolve(); | |
}, sleep); | |
}), | |
); | |
return () => shouldContinue = false; | |
} | |
export { | |
randomBool, | |
randomInt, | |
execAtRandomIntervals, | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Simulates a while loop where the condition is determined by the result of a Promise. | |
* | |
* @param {Function} condition | |
* @param {Function} action | |
* @returns {Promise} | |
*/ | |
export default function promiseWhile(condition, action) { | |
return new Promise((resolve, reject) => { | |
const loop = function () { | |
if (!condition()) { | |
resolve(); | |
} else { | |
Promise.resolve(action()) | |
.then(loop) | |
.catch(reject); | |
} | |
}; | |
loop(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment