From 07a0f30e15d6791330dfa74a8c13c449702eab2f Mon Sep 17 00:00:00 2001 From: Alec Larson <1925840+aleclarson@users.noreply.github.com> Date: Sun, 23 Jun 2024 19:46:00 -0400 Subject: [PATCH] fix(assign): remove inefficiencies in loop Co-authored-by: Kinbaum --- src/object.ts | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/src/object.ts b/src/object.ts index 5561da2a..e90beab0 100644 --- a/src/object.ts +++ b/src/object.ts @@ -2,6 +2,10 @@ import { objectify } from './array' import { toInt } from './number' import { isArray, isObject, isPrimitive } from './typed' +const hasOwnProperty = /* @__PURE__ */ Function.prototype.call.bind( + Object.prototype.hasOwnProperty +) + type LowercasedKeys> = { [P in keyof T & string as Lowercase

]: T[P] } @@ -176,7 +180,7 @@ export const pick = ( ): Pick => { if (!obj) return {} as Pick return keys.reduce((acc, key) => { - if (Object.prototype.hasOwnProperty.call(obj, key)) acc[key] = obj[key] + if (hasOwnProperty(obj, key)) acc[key] = obj[key] return acc }, {} as Pick) } @@ -274,20 +278,15 @@ export const assign = >( override: X ): X => { if (!initial || !override) return initial ?? override ?? {} - - return Object.entries({ ...initial, ...override }).reduce( - (acc, [key, value]) => { - return { - ...acc, - [key]: (() => { - if (isObject(initial[key])) return assign(initial[key], value) - // if (isArray(value)) return value.map(x => assign) - return value - })() - } - }, - {} as X - ) + const merged = { ...initial } + for (const key in override) { + if (hasOwnProperty(override, key)) { + merged[key] = isObject(initial[key]) + ? assign(initial[key], override[key]) + : override[key] + } + } + return merged } /**