sindresorhus / p-map

Map over promises concurrently
MIT License
1.27k stars 58 forks source link

p-flat-map #30

Closed MajorBreakfast closed 3 years ago

MajorBreakfast commented 3 years ago

I encountered the need for p-flat-map. Here's what I came up with:

const pFlatMap = async <Element, NewElements>(
  input: Iterable<Element>,
  mapper: pMap.Mapper<Element, NewElements>,
  options?: pMap.Options
): Promise<FlatArray<NewElements[], 1>[]> => {
  const mapped: NewElements[] = await pMap(input, mapper, options)
  return mapped.flat()
}

Usage example:

const products = await pFlatMap(categories, listProductsForCategory, { concurrency: 50 })

Would it be possible to add this to the collection?

sindresorhus commented 3 years ago

Why not just (await pMap(…)).flat()?

MajorBreakfast commented 3 years ago

I used pFlatMap for better readability. With (await pMap(…)).flat() the intention behind the code was less obvious.

sindresorhus commented 3 years ago

I personally think the intention is quite clear, even more so than pFlatMap.

septatrix commented 4 months ago

Why not just (await pMap(…)).flat()?

Apart from the IMO worse readability due to the required parentheses there is also the disadvantage of requiring slightly more memory. That, however, would also not be solved by the simple implementation proposed above but would require touching more code

septatrix commented 4 months ago

Why not just (await pMap(…)).flat()?

Another limitation which more people might be stumble upon is that this simply not possible when using pMapIterable. In those cases one has to construct a nested loop which is definitely less readable than pFlatMapIterable