asyncMap<T, TRet> function

Future<Map<T, TRet>> asyncMap<T, TRet>(
  1. List<T> items,
  2. Future<TRet> selector(
    1. T
    ), {
  3. int maxConcurrency = 4,
})

Maps a list of values to a new Map using an asynchronous selector function with concurrency control.

This function processes items concurrently (up to maxConcurrency at a time) and returns a Map where each input item is mapped to its corresponding result.

items - The input list to map through. selector - The async selector to apply to each element. maxConcurrency - The maximum number of concurrent operations (default is 4).

Returns a Map of inputs to results.

Example:

final input = [1, 2, 3, 4, 5];
final results = await asyncMap(
  input,
  (x) async => x * 2,
  maxConcurrency: 2,
);
// results: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10}

Implementation

Future<Map<T, TRet>> asyncMap<T, TRet>(
  List<T> items,
  Future<TRet> Function(T) selector, {
  int maxConcurrency = 4,
}) async {
  if (items.isEmpty) {
    return {};
  }

  Stream<MapEntry<T, TRet>> processItem(T item) {
    return Stream.fromFuture(
      selector(item).then((value) => MapEntry(item, value)),
    );
  }

  final results = await Stream.fromIterable(
    items,
  ).flatMap(processItem, maxConcurrent: maxConcurrency).toList();

  return Map.fromEntries(results);
}