Skip to content

Instantly share code, notes, and snippets.

@Floofies
Last active September 9, 2022 11:28
Show Gist options
  • Save Floofies/4f570de20b10cf64db672133797ce62b to your computer and use it in GitHub Desktop.
Save Floofies/4f570de20b10cf64db672133797ce62b to your computer and use it in GitHub Desktop.
Returns a Promise which resolves with a new Array, containing only values which passed the test.
/**
* promiseFilter - Returns a Promise which resolves with a new Array, containing only values which passed the test.
* @param {Array} array An Array from which to filter values into a new Array.
* @param {callback} test A callback function which must return a Promise, which must resolve with a Boolean.
* @callback test
* @param {any} value The current value from `array`.
* @param {Number} index The current index being used to access `array`.
* @param {Array} array The Array being iterated through, `array`.
* @returns {Promise} A Promise which resolves with a new Array containing values which passed the test.
*/
function promiseFilter(array, test) {
return Promise.all(
array.map((val, acc) => test(val, acc, array))
).then(
results => resolve(array.filter((val, acc) => results[acc]))
);
}
if (module !== undefined) module.exports = promiseFilter;
/**
* How To Use
* Below is an example dataset, test, and usage.
* The test returns `true` if the number is divisible by 2, or false if otherwise.
* -----------
const numberArray = [0,1,2,3,4,5,6,7,8,9];
const test = (value, index, array) => value % 2 === 0;
promiseFilter(numberArray, test).then(console.log);
* ------------
* Logs the following: [0,2,4,6,8]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment