Created
November 1, 2018 22:20
-
-
Save rpgeeganage/4887a8bbd2494d2d5809449442792691 to your computer and use it in GitHub Desktop.
ForEach method
This file contains hidden or 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
// Signature of the callback | |
type CallBackForEach<T> = ( | |
value: T, | |
index?: number, | |
collection?: T[] | |
) => Promise<void>; | |
/** | |
* Async ForEach function | |
* | |
* @export | |
* @template T | |
* @param {T[]} elements | |
* @param {CallBackForEach<T>} cb | |
* @returns {Promise<void>} | |
*/ | |
async function aForEach<T>( elements: T[], cb: CallBackForEach<T> ): Promise<void> { | |
for (const [index, element] of elements.entries()) { | |
await cb(element, index, elements); | |
} | |
} | |
// You can use as follows | |
const array = [1, 2, 3, 4]; | |
const output: number[] = []; | |
await aForEach<number>(array, async (i) => { | |
output.push(i); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment