import { isObject } from "./is" type Predicate = (value: any, path: string[]) => R export type MappedObject = { [Prop in keyof T]: T[Prop] extends Array ? MappedObject[] : T[Prop] extends Record ? MappedObject : K } export type WalkObjectStopFn = (value: any, path: string[]) => boolean export interface WalkObjectOptions { stop?: WalkObjectStopFn | undefined getKey?(prop: string, value: any): string } type Nullable = T | null | undefined const isNotNullish = (element: Nullable): element is T => element != null export function walkObject( target: T, predicate: Predicate, options: WalkObjectOptions = {}, ): MappedObject>> { const { stop, getKey } = options function inner(value: any, path: string[] = []): any { if (isObject(value) || Array.isArray(value)) { const result: Record = {} for (const [prop, child] of Object.entries(value)) { const key = getKey?.(prop, child) ?? prop const childPath = [...path, key] if (stop?.(value, childPath)) { return predicate(value, path) } const next = inner(child, childPath) if (isNotNullish(next)) { result[key] = next } } return result } return predicate(value, path) } return inner(target) } export function mapObject(obj: any, fn: (value: any) => any) { if (Array.isArray(obj)) return obj.map((value) => { return isNotNullish(value) ? fn(value) : value }) if (!isObject(obj)) { return isNotNullish(obj) ? fn(obj) : obj } return walkObject(obj, (value) => fn(value)) }