Created
November 1, 2018 22:23
-
-
Save rpgeeganage/ab06a7f644052dfb1519333a0491c6a9 to your computer and use it in GitHub Desktop.
Map method
This file contains 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 CallBackMap<T, R> = ( | |
value: T, | |
index?: number, | |
collection?: T[] | |
) => Promise<R>; | |
/** | |
* Async Map function | |
* | |
* @export | |
* @template T | |
* @template R | |
* @param {T[]} elements | |
* @param {CallBackMap<T, R>} cb | |
* @returns {Promise<R[]>} | |
*/ | |
async function aMap<T, R>( | |
elements: T[], | |
cb: CallBackMap<T, R> | |
): Promise<R[]> { | |
const mappedResults: R[] = []; | |
for (const [index, element] of elements.entries()) { | |
const mappedResult = await cb(element, index, elements); | |
mappedResults.push(mappedResult); | |
} | |
return mappedResults; | |
} | |
// You can use as follows | |
const array = [1, 2, 3, 4]; | |
const output = await aMap<number, string>(array, async (i) => { | |
return Promise.resolve(i.toString(10)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment