rollup<T, R, K> function Grouping data

Map<K, R> rollup<T, R, K>(
  1. Iterable<T> iterable,
  2. R reduce(
    1. List<T>
    ),
  3. K key(
    1. T
    )
)

Groups and reduces the specified iterable of values into an Map from key to value.

For example, given some data:

final data = [
  {"name": "jim",   "amount": "34.0",   "date": "11/12/2015"},
  {"name": "carl",  "amount": "120.11", "date": "11/12/2015"},
  {"name": "stacy", "amount": "12.01",  "date": "01/04/2016"},
  {"name": "stacy", "amount": "34.05",  "date": "01/04/2016"}
];

To count the number of elements by name:

rollup(data, (v) => v["length"], (d) => d["name"])

This produces:

{
  "jim": 1,
  "carl": 1,
  "stacy": 2
};

To count the number of elements by more than one key:

rollup(data, (v) => v["length"], (d) => (d["name"], d["date"]));

This produces:

{
  ("jim", "11/12/2015"): 1,
  ("carl", "11/12/2015"): 1,
  ("stacy", "01/04/2016"): 2
};

Implementation

Map<K, R> rollup<T, R, K>(
    Iterable<T> iterable, R Function(List<T>) reduce, K Function(T) key) {
  var groups = <K, List<T>>{};
  for (var value in iterable) {
    (groups[key(value)] ??= []).add(value);
  }
  return groups.map((key, value) => MapEntry(key, reduce(value)));
}