Last active
June 14, 2022 18:43
-
-
Save James-Firth/220b40e4b66540063e93e1f105657131 to your computer and use it in GitHub Desktop.
This file contains 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
// Taken from | |
// https://advancedweb.hu/how-to-use-async-functions-with-array-filter-in-javascript/ | |
// and | |
// https://patrickmuff.ch/blog/async-filter-array-typescript/ | |
/** | |
* @param {Array} array The array to perform the map on | |
* @param {Function} callback to be performed on each array element | |
* @return {Promise} Which returns an array of the results, in order. | |
*/ | |
function mapAsync(array, callback) { | |
return Promise.all(array.map(callback)); | |
} | |
/** | |
* @param {Array} array The array to filter | |
* @param {Function} callback The async function that MUST return truthy/falsey values to filter the array | |
* @return {Promise} Which returns a the filtered array | |
*/ | |
async function filterAsync(array, callback) { | |
// filterMap will have an array of values (ideally booleans but may be simply truthy/falsey) | |
// this matches the length of array | |
// this happens asynchronously | |
const filterMap = await mapAsync(array, callback); | |
// then we simply filter by comparing the mapped array with the one passed in. | |
// eslint-disable-next-line security/detect-object-injection | |
return array.filter((_, index) => filterMap[index]); | |
} | |
/** | |
* Mostly for testing | |
* @param {Number} seconds number of seconds to sleep | |
*/ | |
async function sleep(seconds, callback) { | |
if (Number.isNaN(seconds)) throw new TypeError('Seconds must be a number'); | |
return new Promise((resolve) => { | |
if (callback) { | |
setTimeout(() => resolve(callback()), seconds * 1000); | |
} else { | |
setTimeout(resolve, seconds * 1000); | |
} | |
}); | |
} | |
async function timeout(ms) { | |
return new Promise((resolve) => setTimeout(resolve, ms)); | |
} | |
async function loopWhile(rerunAwaitable, conditionAwaitable, ms, { verbose = false } = {}) { | |
/* eslint-disable no-await-in-loop */ | |
while (await conditionAwaitable()) { | |
if (verbose) console.log('Loop While: Running Reunable Awaitable'); | |
await rerunAwaitable(); | |
if (verbose) console.log(`Loop While: Waiting ${ms} ms`); | |
await timeout(ms); | |
} | |
if (verbose) console.log('Loop While: Finished'); | |
/* eslint-enable no-await-in-loop */ | |
} | |
module.exports = { filterAsync, mapAsync, sleep, timeout, loopWhile }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment