/** * Copied from chakra-ui, license MIT * Accessed 2021-12-26, commit October 19th, 2021 * See also: https://github.com/chakra-ui/chakra-ui/blob/cd0893c/packages/utils/src/walk-object.ts */ import { isArray, isObject } from "./assertion"; import { fromEntries } from "./object"; export type WalkObjectPredicate = ( value: unknown, path: string[], ) => Leaf; export type MappedLeavesObject = { [Prop in keyof Obj]: Obj[Prop] extends Array ? MappedLeavesObject[] : Obj[Prop] extends object ? MappedLeavesObject : LeafType; }; export function walkObject( target: Target, predicate: WalkObjectPredicate, ): MappedLeavesObject>> { function inner(value: unknown, path: string[] = []): any { if (isArray(value)) { return value.map((item, index) => inner(item, [...path, String(index)])); } if (isObject(value)) { return fromEntries( Object.entries(value).map(([key, child]) => [ key, inner(child, [...path, key]), ]), ); } return predicate(value, path); } return inner(target); }