UNPKG

object-fns

Version:

Object utility functions

65 lines (58 loc) 1.34 kB
export type FilterCallback = (value: any, key: string, obj: object) => boolean; export function map( obj: object, fn: (value: any, key: string, obj: object) => any, ): object { const result = {}; for (const key in obj) { const value = fn(obj[key], key, obj); if (value !== undefined) { result[key] = value; } } return result; } export function filterBy(obj: object, keys: string[]): object { const result = {}; for (const key of keys) { if (key in obj) { result[key] = obj[key]; } } return result; } export function filter(obj: object, fn: FilterCallback): object { const result = {}; for (const key in obj) { if (fn(obj[key], key, obj)) { result[key] = obj[key]; } } return result; } export function findKey(obj: object, fn: FilterCallback): string { for (const key in obj) { if (fn(obj[key], key, obj)) { return key; } } } export function all(obj: object, fn: FilterCallback): boolean { for (const key in obj) { if (!fn(obj[key], key, obj)) { return false; } } return true; } export function reduce<T = any>( obj: object, fn: (prev: T, value: any, key: string, obj: object) => T, start: T, ): T { let result: T = start; for (const key in obj) { result = fn(result, obj[key], key, obj); } return result; }