All files mapRecord.ts

100% Statements 13/13
100% Branches 0/0
100% Functions 5/5
100% Lines 10/10

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  8x                                                     8x 1x     8x       1x 3x 3x   3x 3x 3x      
import { Pred } from './_types';
import { purry } from './purry';
 
/**
 * Loops each record element and maps against provided function.
 * @param record The target object.
 * @param fn Mapping function.
 * @returns The new record.
 * @signature
 *    P.flatMapRecord(record, fn)
 * @signature
 *    P.flatMapRecord(record, fn)
 * @example
 *    P.flatMapRecord({ a: 1, b: 2, c: 3 }, ([k,v]) => [[k, v * 2], [k + "_abc", v * 2]]) // => { a: 2, a_abc: 2, b: 4, b_abc: 4, c: 6, c_abc: 6 }
 *    P.flatMapRecord({ a: 1, b: 2, c: 3 }, ([k,v]) => [[k, v * 2], [k + "_abc", v * 2]]) // => { a: 2, a_abc: 2, b: 4, b_abc: 4, c: 6, c_abc: 6 }
 * @category Object, Pipe
 */
export function mapRecord<
  T extends Record<string, unknown>,
  K extends string,
  V
>(record: T, fn: Pred<[keyof T, T[keyof T]], [K, V]>): Record<K, V>;
 
export function mapRecord<
  T extends Record<string, unknown>,
  K extends string,
  V extends unknown
>(fn: (v: [keyof T, T[keyof T]]) => [K, V]): (record: T) => Record<K, V>;
export function mapRecord() {
  return purry(_mapRecord(), arguments);
}
 
const _mapRecord = () => <T extends { [k: string]: any }, K extends string, V>(
  rec: T,
  fn: (v: [keyof T, T[keyof T]]) => [K, V]
) => {
  return Object.entries(rec)
    .map(([k, v]) => {
      return fn([k as keyof T, (v as unknown) as T[keyof T]]);
    })
    .reduce((acc, [k, v]) => {
      acc[k] = v;
      return acc;
    }, {} as Record<K, V>);
};