All files / array/operator countBy.ts

100% Statements 9/9
100% Branches 2/2
100% Functions 2/2
100% Lines 8/8

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        1x 6x 9x 9x 12x 12x 12x   5x      
import {Dictionary, PropertyProjection} from 'fnxt/fnxt-types';
 
type Pair<F> = [F, number]
 
export const countBy = <E, F extends string | number = string | number>(projection: PropertyProjection<E, F>) =>
  (array: E[]): [F, number][] => {
    const dict: Dictionary<Pair<F>> = {};
    for (const e of array) {
      const key = projection(e);
      const [_, v]: Pair<F> = dict[key] || [key, 0];
      dict[key] = [key, v + 1] as Pair<F>;
    }
    return Object.values(dict);
  };