Skip to content

Instantly share code, notes, and snippets.

@rpgeeganage
Created November 1, 2018 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpgeeganage/45166ade6a34ff102416d43b27967d96 to your computer and use it in GitHub Desktop.
Save rpgeeganage/45166ade6a34ff102416d43b27967d96 to your computer and use it in GitHub Desktop.
Filter method
// Signature of the callback
type CallBackFilter<T> = (
value: T,
index?: number,
collection?: T[]
) => Promise<boolean>;
/**
* Async Filter function
*
* @export
* @template T
* @param {T[]} elements
* @param {CallBackFilter<T>} cb
* @returns {Promise<T[]>}
*/
async function aFilter<T>(
elements: T[],
cb: CallBackFilter<T>
): Promise<T[]> {
const filteredResults: T[] = [];
for (const [index, element] of elements.entries()) {
if (await cb(element, index, elements)) {
filteredResults.push(element);
}
}
return filteredResults;
}
// You can use as follows
const array = [1, 2, 3, 4];
const output = await aFilter<number>(array, async (i) => {
return Promise.resolve(i > 2);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment