diff --git a/packages/object-util/__tests__/index.test.ts b/packages/object-util/__tests__/index.test.ts index 27fc12b..6fa714d 100644 --- a/packages/object-util/__tests__/index.test.ts +++ b/packages/object-util/__tests__/index.test.ts @@ -1,6 +1,6 @@ /// -import { objectSize, objectToArray, objectMap, objectSort, cloneObject, objectEqual, objectKeys, objectSet, objectLoop } from '../src/ObjectUtil' +import { objectSize, objectToArray, objectMap, objectSort, cloneObject, objectEqual, objectKeys, objectSet, objectLoop, objectClone } from '../src/ObjectUtil' describe('Object Map tests', () => { it('should works', () => { @@ -106,6 +106,34 @@ describe('Object Clone Tests', () => { clone.toto = 'third' expect(clone).not.toEqual(obj) }) + + it('Should keep types', () => { + const obj = { + a: [], + b: '10', + c: 10, + d: {}, + e: [10], + f: {g: 10} + } + const clone = objectClone(obj) + expect(clone).toEqual(obj) + }) + + it ('Should clone any types', () => { + const obj = { + a: [], + b: '10', + c: 10, + d: {}, + e: [10], + f: {g: 10} + } + objectLoop(obj, (subObj) => { + const clone = objectClone(subObj) + expect(clone).toEqual(subObj) + }) + }) }) describe('Object Set Tests', () => { @@ -171,4 +199,11 @@ describe('Object Equal Test', () => { it('should not be differently equal', () => { expect(objectEqual({pouet: true}, {})).toBe(false) }) + it('should handle every types', () => { + expect(objectEqual({ + a: [10, {b: 'c'}], d: '1', e: 2, f: true, g: null, h: undefined + }, { + a: [10, {b: 'c'}], d: '1', e: 2, f: true, g: null, h: undefined + })).toBe(true) + }) }) diff --git a/packages/object-util/src/ObjectUtil.ts b/packages/object-util/src/ObjectUtil.ts index 36c25d5..d4ca446 100644 --- a/packages/object-util/src/ObjectUtil.ts +++ b/packages/object-util/src/ObjectUtil.ts @@ -19,10 +19,8 @@ export function objectMap(obj: Record, fn: (value: * @param fn the function to run for each childs */ export function objectLoop(obj: Record, fn: (value: T, key: string) => boolean | void): boolean { - for (const key in obj) { - if (!Object.prototype.hasOwnProperty.call(obj, key)) { - continue - } + const keys = objectKeys(obj) + for (const key of keys) { const stop = fn(obj[key], key) if (stop === false) { return false @@ -87,6 +85,17 @@ export function cloneObject>(obj: T): T { * @param obj the object to clone */ export function objectClone>(obj: T): T { + if (typeof obj !== 'object') { + const v = obj + return v + } + if (Array.isArray(obj)) { + const arr: Array = [] + for (const item of obj) { + arr.push(objectClone(item)) + } + return arr as unknown as T + } const clone: Partial = {} objectLoop(obj, (value, key) => { if (typeof value === 'object' && value != null) {