All files groupBy.ts

100% Statements 22/22
87.5% Branches 7/8
100% Functions 9/9
100% Lines 21/21

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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 718x                                               8x 4x           24x     8x       8x 8x 24x 24x 40x 28x   40x   24x 8x 24x   8x   16x   8x     8x               8x 4x      
import { purry } from './purry';
import { PredIndexedOptional, PredIndexed } from './_types';
 
/**
 * Splits a collection into sets, grouped by the result of running each value through `fn`.
 * @param items the items to group
 * @param fn the grouping function
 * @signature
 *    P.groupBy(array, fn)
 * @signature
 *    P.groupBy(fn)(array)
 * @example
 *    P.groupBy(['one', 'two', 'three'], x => x.length) // => {3: ['one', 'two'], 5: ['three']}
 *    P.pipe(['one', 'two', 'three'], P.groupBy(x => x.length)) // => {3: ['one', 'two'], 5: ['three']}
 * @category Array, Pipe
 */
export function groupBy<T, K extends keyof any>(
  items: readonly T[],
  fn: (item: T) => K | ReadonlyArray<K>
): Record<K, T[]>;
 
export function groupBy<T, K extends keyof any>(
  fn: (item: T) => K | ReadonlyArray<K>
): (array: readonly T[]) => Record<K, T[]>;
export function groupBy() {
  return purry(_groupBy(false), arguments);
}
 
function isArray<T>(
  data: T
): data is Extract<T, Array<any> | ReadonlyArray<any>> {
  return Array.isArray(data);
}
 
const _groupBy = (indexed: boolean) => <T, K extends keyof any>(
  array: T[],
  fn: PredIndexedOptional<T, K | ReadonlyArray<K>>
) => {
  const ret: Record<keyof any, T[]> = {};
  array.forEach((item, index) => {
    const value = indexed ? fn(item, index, array) : fn(item);
    const addToGroup = (key: K, value: T) => {
      if (!ret[key]) {
        ret[key] = [];
      }
      ret[key].push(value);
    };
    if (isArray(value)) {
      value.forEach(key => {
        addToGroup(key, item);
      });
      return;
    }
    addToGroup(value, item);
  });
  return ret;
};
 
export namespace groupBy {
  export function indexed<T, K extends keyof any>(
    array: readonly T[],
    fn: PredIndexed<T, K | ReadonlyArray<K>>
  ): Record<K, T[]>;
  export function indexed<T, K extends keyof any>(
    fn: PredIndexed<T, K | ReadonlyArray<K>>
  ): (array: readonly T[]) => Record<K, T[]>;
  export function indexed() {
    return purry(_groupBy(true), arguments);
  }
}