All files / iterable/src groupBy.ts

100% Statements 6/6
100% Branches 4/4
100% Functions 3/3
100% Lines 5/5

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32  1x                                     1x     1x   4x 4x          
import { Mapper } from "@benneq/function";
import { reduce } from "./reduce";
 
/**
 * Creates a {@link Function} that groups all elements of an {@link Iterable}
 * by using a {@link Mapper} function and returns a {@link Map} containing the
 * grouped values for each mapped key.
 *
 * @example
 * ```ts
 * const groupByEvenOdd = groupBy(isEven);
 * const result = groupByEvenOdd([1,2,1,3]);
 * console.log(result); // Map([[1, [1,1,3]], [0, [2]]])
 * ```
 *
 * @typeParam T - the {@link Iterable} value type
 * @typeParam K - the {@link Map} key type
 * @param mapper - the key {@link Mapper} function
 * @returns a {@link Map} containing the grouped values
 */
export const groupBy = <T, K>(
  mapper: Mapper<T, K>
): ((iterable: Iterable<T>) => Map<K, T[]>) => {
  return reduce(
    (acc, value, key = mapper(value), values = acc.get(key) ?? []) => {
      values.push(value);
      return acc.set(key, values);
    },
    new Map<K, T[]>()
  );
};