by<K, V> method
Groups the iterable's elements by keys returned by by
before being folded using as
.
The order of elements passed to as
is non-deterministic when the iterable is unordered, i.e. HashSet.
Example
final list = [('a', 1), ('a', 2), ('b', 4)];
final counts = list.group.by((e) => e.$1, as: (count, e) => (count ?? 0) + e.$2);
print(counts); // {'a': 3, 'b': 4}
Implementation details
Computing K
is assumed to be cheap. Hence, K
s are recomputed each time rather than cached.
Implementation
@useResult Map<K, V> by<K, V>(Select<E, K> by, {required V Function(V? previous, E current) as}) {
final results = <K, V>{};
for (final element in _iterable) {
final key = by(element);
results[key] = as(results[key], element);
}
return results;
}