Skip to content

Instantly share code, notes, and snippets.

@rpgeeganage
Created November 1, 2018 22:13
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/4b6fd8de66d53ab4322a1bedf2203963 to your computer and use it in GitHub Desktop.
Save rpgeeganage/4b6fd8de66d53ab4322a1bedf2203963 to your computer and use it in GitHub Desktop.
Find method
// Signature of the callback
type CallBackFind<T> = (
value: T,
index?: number,
collection?: T[]
) => Promise<boolean>;
/**
* Async Find function
*
* @export
* @template T
* @param {T[]} elements
* @param {CallBackFind<T>} cb
* @returns {Promise<T | undefined>}
*/
async function aFind<T>( elements: T[], cb: CallBackFind<T> ): Promise<T | undefined> {
for (const [index, element] of elements.entries()) {
if (await cb(element, index, elements)) {
return element;
}
}
return undefined;
}
// You can use as follows
const array = [1, 2, 3, 4];
const output = await aFind<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