Skip to content

Commit

Permalink
Extracted inner recursive funtion out of the crush function for bette…
Browse files Browse the repository at this point in the history
…r performance
  • Loading branch information
stefaanv authored and aleclarson committed Jul 19, 2024
1 parent 6a0729e commit b3eef45
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions src/object/crush.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,20 @@ type Primitive =
| undefined
| null;

const crushToPvArray: (
obj: object,
path: string,
) => Array<{ p: string; v: Primitive }> = (obj: object, path: string) =>
Object.entries(obj).flatMap(([key, value]) =>
isPrimitive(value) || isDate(value)
? { p: path === "" ? key : `${path}.${key}`, v: value }
: crushToPvArray(value, path === "" ? key : `${path}.${key}`),
);

export function crush<TValue extends object>(
value: TValue,
): Record<string, Primitive> | Record<string, never> {
if (!value) return {};
const crushToPvArray: (
obj: object,
path: string,
) => Array<{ p: string; v: Primitive }> = (obj: object, path: string) =>
Object.entries(obj).flatMap(([key, value]) =>
isPrimitive(value) || isDate(value)
? { p: path === "" ? key : `${path}.${key}`, v: value }
: crushToPvArray(value, path === "" ? key : `${path}.${key}`),
);

const result = objectify(
crushToPvArray(value, ""),
Expand Down

0 comments on commit b3eef45

Please sign in to comment.