asyncReduce<T, TAcc> function
Reduces a list using an asynchronous selector function.
Like Iterable.fold, but each step is asynchronous. Items are processed
sequentially, with each step waiting for the previous one to complete.
items - The input list to reduce.
selector - The async reducer function that takes the accumulator and
current item, returning the new accumulator value.
seed - The initial value for the accumulator.
Returns the final accumulated value.
Example:
final input = [1, 2, 3, 4, 5];
final sum = await asyncReduce(
input,
(acc, x) async => acc + x,
0,
);
// sum: 15
Implementation
Future<TAcc> asyncReduce<T, TAcc>(
List<T> items,
Future<TAcc> Function(TAcc acc, T item) selector,
TAcc seed,
) async {
var acc = seed;
for (final item in items) {
acc = await selector(acc, item);
}
return acc;
}