All files flatMapRecord.ts

100% Statements 15/15
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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69  8x                                                                                       8x 2x     8x               2x 6x 6x     12x 12x   6x      
import { Pred } from './_types';
import { purry } from './purry';
 
/**
 * Loops each record element and flatMaps against provided function.
 * @param record The target object.
 * @param fn Mapping function.
 * @returns The new record.
 * @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 }
 * @data_first
 * @pipeable
 * @category Object
 */
export function flatMapRecord<
  T extends Record<string, unknown>,
  K extends string,
  V
>(
  record: T,
  fn: Pred<[keyof T, T[keyof T]], ReadonlyArray<[K, V]>>
): Record<K, V>;
 
/**
 * Loops each record element and flatMaps against provided function.
 * @param record The target object.
 * @param fn Mapping function.
 * @returns The new record.
 * @signature
 *    P.pipe(record, P.flatMapRecord(fn))
 * @example
 *    P.pipe(({ a: 1, b: 2, c: 3 }, P.flatMapRecord(([k,v]) => [[k, v * 2], [k + "_abc", v * 2]])) // => { a: 2, a_abc: 2, b: 4, b_abc: 4, c: 6, c_abc: 6 }
 * @data_last
 * @pipeable
 * @category Object
 */
export function flatMapRecord<
  T extends Record<string, unknown>,
  K extends string,
  V extends unknown
>(
  fn: (v: [keyof T, T[keyof T]]) => ReadonlyArray<[K, V]>
): (record: T) => Record<K, V>;
export function flatMapRecord() {
  return purry(_flatMapRecord(), arguments);
}
 
const _flatMapRecord = () => <
  T extends { [k: string]: any },
  K extends string,
  V
>(
  rec: T,
  fn: (v: [keyof T, T[keyof T]]) => ReadonlyArray<[K, V]>
) => {
  return Object.entries(rec)
    .map(([k, v]) => {
      return fn([k as keyof T, (v as unknown) as T[keyof T]]);
    })
    .reduce((acc, w) => {
      for (const [k, v] of w) {
        acc[k] = v;
      }
      return acc;
    }, {} as Record<K, V>);
};