diff --git a/packages/object-util/__tests__/index.test.ts b/packages/object-util/__tests__/index.test.ts index 07ba72d..46b32e1 100644 --- a/packages/object-util/__tests__/index.test.ts +++ b/packages/object-util/__tests__/index.test.ts @@ -158,6 +158,18 @@ describe('Object Clone Tests', () => { ;(clone[2][0] as string) = 'zero' expect(clone).not.toEqual(obj) }) + + + it('should clone with Object.freeze', () => { + const obj = Object.freeze({ + pouet: 'first', + toto: 'second' + }) + const clone = objectClone>(obj) + expect(clone).toEqual(obj) + clone.pouet = 'third' + expect(clone).not.toEqual(obj) + }) }) describe('Object Set Tests', () => { @@ -237,7 +249,8 @@ describe('Object Clean Tests', () => { const obj = {a: '', b: null, c: undefined} objectClean(obj) expect(obj).toEqual({a: '', b: null}) - + }) + it('should not clean when options.cleanUndefined is false', () => { const obj2 = {a: '', b: null, c: undefined} objectClean(obj2, {cleanUndefined: false}) expect(obj2).toEqual({a: '', b: null, c: undefined}) @@ -268,6 +281,10 @@ describe('Object Omit Tests', () => { const obj = {a: 'a', b: 'c', c: 'b'} expect(objectOmit(obj, 'b', 'd')).toEqual({a: 'a', c: 'b'}) }) + it('should work with Object.freeze', () => { + const obj = {a: 'a', b: 'c', c: 'b'} + expect(objectOmit(Object.freeze(obj), 'b', 'd')).toEqual({a: 'a', c: 'b'}) + }) }) describe('Is Object Tests', () => { diff --git a/packages/object-util/src/ObjectUtil.ts b/packages/object-util/src/ObjectUtil.ts index 01bd58d..30833fc 100644 --- a/packages/object-util/src/ObjectUtil.ts +++ b/packages/object-util/src/ObjectUtil.ts @@ -109,7 +109,7 @@ export function cloneObject>(obj: T): T { * @param obj the object to clone * @returns the clone of the object */ -export function objectClone>(obj: T): T { +export function objectClone>(obj: T, options?: {deep?: boolean}): T { mustBeObject(obj) if (Array.isArray(obj)) { const arr: Array = [] @@ -124,7 +124,7 @@ export function objectClone>(obj: T): T { } const clone: Partial = {} objectLoop(obj, (value, key) => { - if (typeof value === 'object' && value != null) { + if (typeof value === 'object' && value != null && (typeof options?.deep === 'undefined' || options.deep)) { clone[key as Extract] = objectClone(value) return } @@ -228,7 +228,7 @@ export function objectClean(obj: Record, options?: {cleanUndefined? * @returns the cloned object */ export function objectOmit = Record>(obj: T, ...keys: Array): T { - const cloned = obj + const cloned = objectClone(obj, {deep: false}) for (const key of keys) { if (key in cloned) { delete cloned[key]