All files filterRecord.ts

100% Statements 10/10
100% Branches 0/0
100% Functions 4/4
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 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  8x                                             8x 2x     8x               2x   4x 4x 4x      
import { Pred } from './_types';
import { purry } from './purry';
 
/**
 * Loops each record element and match against provided predicate.
 * @param record The object to filter.
 * @param fn Predicate function.
 * @returns The new filtered record.
 * @signature
 *    P.filterRecord(record, fn)
 * @signature
 *    P.pipe({ a: 1, b: 2, c: 3 }, P.filterRecord(fn))
 * @example
 *    P.filterRecord({ a: 1, b: 2, c: 3 }, ([k,v]) => [k, v * 2]) // => { a: 2, b: 4, c: 6 }
 *    P.pipe({ a: 1, b: 2, c: 3 }, P.filterRecord(([k,v]) => [k, v * 2]))) // => { a: 2, b: 4, c: 6 }
 * @category Object, Pipe
 */
export function filterRecord<T extends Record<string, unknown>>(
  record: T,
  fn: Pred<[keyof T, T[keyof T]], any>
): Record<keyof T, T[keyof T]>;
export function filterRecord<T extends Record<string, unknown>>(
  fn: (v: [keyof T, T[keyof T]]) => any
): (record: T) => Record<keyof T, T[keyof T]>;
export function filterRecord() {
  return purry(_filterRecord(), arguments);
}
 
const _filterRecord = () => <
  T extends { [k: string]: any },
  K extends string,
  V
>(
  rec: T,
  fn: (v: [keyof T, T[keyof T]]) => any
) => {
  return Object.entries(rec)
    .filter(fn)
    .reduce((acc, [k, v]: [keyof T, T[keyof T]]) => {
      acc[k] = v;
      return acc;
    }, {} as Record<keyof T, T[keyof T]>);
};