Skip to content

Instantly share code, notes, and snippets.

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