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 55 56 57 58 59 60 61 62 63 64 65 66 67 681x                                                                       1x 2x     4x       4x   8x 8x 8x 8x           1x               1x 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
 *    R.indexBy(array, fn)
 * @example
 *    R.indexBy(['one', 'two', 'three'], x => x.length) // => {3: 'two', 5: 'three'}
 * @data_first
 * @indexed
 * @category Array
 */
export function indexBy<T>(array: T[], fn: (item: T) => any): Record<string, T>;
 
/**
 * 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
 *    R.indexBy(fn)(array)
 * @example
 *    R.pipe(
 *      ['one', 'two', 'three'],
 *      R.indexBy(x => x.length)
 *    ) // => {3: 'two', 5: 'three'}
 * @data_last
 * @indexed
 * @category Array
 */
export function indexBy<T>(
  fn: (item: T) => any
): (array: T[]) => Record<string, T>;
 
export function indexBy() {
  return purry(_indexBy(false), arguments);
}
 
const _indexBy = (indexed: boolean) => <T>(
  array: T[],
  fn: PredIndexedOptional<T, any>
) => {
  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: T[],
    fn: PredIndexed<T, any>
  ): Record<string, T>;
  export function indexed<T, K>(
    fn: PredIndexed<T, any>
  ): (array: T[]) => Record<string, T>;
  export function indexed() {
    return purry(_indexBy(true), arguments);
  }
}