Skip to content

Instantly share code, notes, and snippets.

@pmdartus
Created June 10, 2021 06:51
Show Gist options
  • Save pmdartus/aafa8b2a56a7c26d26f7ecf54ffec6ec to your computer and use it in GitHub Desktop.
Save pmdartus/aafa8b2a56a7c26d26f7ecf54ffec6ec to your computer and use it in GitHub Desktop.

Async map

Implement a function asyncMap.

This function produces an array of values by mapping each value in arr through the iteratee function in parallel. The iteratee function accepts a first argument an item from arr and a Node.js style callback (accepting an error as first argument or null and the mapped item as second argument). If the iteratee produces a error the main callback is invoked with the error as first argument, otherwise the main callback is invoked with null as first argument and the array of mapped items as second argument.

function asyncMap(arr, fn, cb) {
    // TODO
}
declare function asyncMap<In, Out>(
    arr: In[], 
    iteratee: (item: In, cb: (err: null | unknown, res: Out) => void) => void, 
    callback: (err: null | unknown, res: Out[]) => void
): void;
asyncMap(
    [1, 2, 3],
    (item, cb) => {
        const squared = item * item;
        setTimeout(() => {
            cb(null, squared);
        }, squared);
    },
    (err, res) => {
        console.log(err, res); // null, [1, 4, 9]
    }
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment