Skip to content

Instantly share code, notes, and snippets.

@Yopadd
Created February 16, 2018 07:15
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Yopadd/d1381e0fdc1aa6bedaeb36b7a8381892 to your computer and use it in GitHub Desktop.
Save Yopadd/d1381e0fdc1aa6bedaeb36b7a8381892 to your computer and use it in GitHub Desktop.
return a flatten map resolved by async function
async function asyncFlatMap (arr, asyncFn) {
return Promise.all(flatten(await asyncMap(arr, asyncFn)))
}
function asyncMap (arr, asyncFn) {
return Promise.all(arr.map(asyncFn))
}
function flatMap (arr, fn) {
return flatten(arr.map(fn))
}
function flatten (arr) {
return [].concat(...arr)
}
module.exports = {
asyncFlatMap,
asyncMap,
flatMap,
flatten
}
@louislepper
Copy link

louislepper commented May 10, 2021

With typescript types / es6 module syntax:

async function asyncFlatMap<T, O>(arr: T[], asyncFn: (t: T) => Promise<O[]>): Promise<O[]> {
    return Promise.all(flatten(await asyncMap(arr, asyncFn)))
}

function flatMap<T, O>(arr: T[], fn: (t: T) => O[]): O[] {
    return flatten(arr.map(fn))
}

function asyncMap<T, O>(arr: T[], asyncFn: (t: T) => Promise<O>): Promise<O[]> {
    return Promise.all(arr.map(asyncFn))
}

function flatten<T>(arr: T[][]): T[] {
    return ([] as T[]).concat(...arr);
}

export {
    asyncFlatMap,
    asyncMap,
    flatMap,
    flatten
}

@peveuve
Copy link

peveuve commented Oct 13, 2022

should you not flat first and then map? Your map executes on both single elements and arrays of elements.

@Yopadd
Copy link
Author

Yopadd commented Oct 13, 2022

@peveuve If you want flat first you don't need a function. You could write flatten(arr).map(fn).
Actually, this gist is a little bit obsolete because now we have official flatMap and flat

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment