Skip to content

Instantly share code, notes, and snippets.

@rpgeeganage
Created November 1, 2018 22:23
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/ab06a7f644052dfb1519333a0491c6a9 to your computer and use it in GitHub Desktop.
Save rpgeeganage/ab06a7f644052dfb1519333a0491c6a9 to your computer and use it in GitHub Desktop.
Map method
// 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