groupedStats<T, K> function
Groups items by keyOf and computes a NumericStats bundle over
valueOf for each group, in a single pass. A key appears only if at least
one item maps to it, so every returned NumericStats has count ≥ 1 (no
divide-by-zero in mean). Insertion order of first-seen keys is preserved.
Example:
groupedStats(rows, keyOf: (r) => r.country, valueOf: (r) => r.sales);
// {US: NumericStats(count: 2, sum: 15, min: 5, max: 10, mean: 7.5), ...}
Audited: 2026-06-12 11:26 EDT
Implementation
Map<K, NumericStats> groupedStats<T, K>(
Iterable<T> items, {
required K Function(T) keyOf,
required num Function(T) valueOf,
}) {
final Map<K, _Acc> accumulators = <K, _Acc>{};
for (final T item in items) {
accumulators.putIfAbsent(keyOf(item), () => _Acc()).add(valueOf(item));
}
return accumulators.map(
(K key, _Acc acc) => MapEntry<K, NumericStats>(key, acc.toStats()),
);
}