All files indexBy.ts

100% Statements 13/13
75% Branches 3/4
100% Functions 6/6
100% Lines 12/12

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 558x                                                   8x 2x     8x       4x 8x 8x 8x 8x       8x               8x 2x      
import { purry } from './purry';
import { PredIndexedOptional, PredIndexed } from './_types';
 
/**
 * Converts a list of objects into an object indexing the objects by the given key.
 * @param array the array
 * @param fn the indexing function
 * @signature
 *    P.indexBy(array, fn)
 *    P.indexBy(fn)(array)
 * @example
 *    P.indexBy(['one', 'two', 'three'], x => x.length) // => {3: 'two', 5: 'three'}
 *    P.pipe(
 *      ['one', 'two', 'three'],
 *      P.indexBy(x => x.length)
 *    ) // => {3: 'two', 5: 'three'}
 * @category Array, Pipe
 */
export function indexBy<T>(
  array: readonly T[],
  fn: (item: T) => any
): Record<string, T>;
export function indexBy<T>(
  fn: (item: T) => string | number
): (array: readonly T[]) => Record<string, T>;
 
export function indexBy() {
  return purry(_indexBy(false), arguments);
}
 
const _indexBy = (indexed: boolean) => <T>(
  array: T[],
  fn: PredIndexedOptional<T, string | number>
) => {
  return array.reduce((ret, item, index) => {
    const value = indexed ? fn(item, index, array) : fn(item);
    const key = String(value);
    ret[key] = item;
    return ret;
  }, {} as Record<string, T>);
};
 
export namespace indexBy {
  export function indexed<T, K>(
    array: readonly T[],
    fn: PredIndexed<T, any>
  ): Record<string, T>;
  export function indexed<T, K>(
    fn: PredIndexed<T, any>
  ): (array: readonly T[]) => Record<string, T>;
  export function indexed() {
    return purry(_indexBy(true), arguments);
  }
}