From 1882032c8e7bdb84be02a0744c95fbcf7236d70b Mon Sep 17 00:00:00 2001 From: Alex S <49695018+alexs-mparticle@users.noreply.github.com> Date: Wed, 20 Mar 2024 13:05:30 -0400 Subject: [PATCH] fix: Create a simple merge object utility (#849) --- src/utils.ts | 5 +++++ test/src/tests-utils.ts | 47 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/src/utils.ts b/src/utils.ts index e9eb8356..51af1c09 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -223,6 +223,10 @@ const isStringOrNumber = (value: any): boolean => const isEmpty = (value: Dictionary | null | undefined): boolean => value == null || !(Object.keys(value) || value).length; +const mergeObjects = (...objects: T[]): T => { + return Object.assign({}, ...objects); +}; + export { createCookieString, revertCookieString, @@ -251,4 +255,5 @@ export { isDataPlanSlug, isEmpty, isValidCustomFlagProperty, + mergeObjects, }; diff --git a/test/src/tests-utils.ts b/test/src/tests-utils.ts index a07a4ab5..5fb685c9 100644 --- a/test/src/tests-utils.ts +++ b/test/src/tests-utils.ts @@ -12,6 +12,7 @@ import { isObject, isStringOrNumber, isValidCustomFlagProperty, + mergeObjects, parseNumber, parseStringOrNumber, replaceApostrophesWithQuotes, @@ -373,4 +374,50 @@ describe('Utils', () => { expect(isValidCustomFlagProperty(undefined), 'undefined').to.equal(false); }); }); + + describe('#mergeObjects', () => { + it('should merge objects', () => { + const obj1 = { foo: 'bar' }; + const obj2 = { fizz: 'buzz' }; + + expect(mergeObjects(obj1, obj2)).to.deep.equal({ + foo: 'bar', + fizz: 'buzz', + }); + }); + + it('should override values with the same keys in the order they appear, with the subsequent objects taking priority', () => { + const obj1 = { foo: 'bar', flip: 'flop' }; + const obj2 = { fizz: 'buzz', narf: 'poit' }; + const obj3 = { foo: 'baz' }; + + expect(mergeObjects(obj1, obj2, obj3)).to.deep.equal({ + foo: 'baz', + fizz: 'buzz', + flip: 'flop', + narf: 'poit', + }); + }); + + it('should merge objects with nested objects', () => { + const obj1 = { foo: { bar: 'baz' } }; + const obj2 = { fizz: { buzz: 'fizzbuzz' } }; + + expect(mergeObjects(obj1, obj2)).to.deep.equal({ + foo: { bar: 'baz' }, + fizz: { buzz: 'fizzbuzz' }, + }); + }); + + it('should return a copy of the original object', () => { + const obj1 = { foo: 'bar' }; + const obj2 = { fizz: 'buzz' }; + + const merged = mergeObjects(obj1, obj2); + merged.foo = 'not-bar'; + + expect(obj1.foo).to.equal('bar'); + expect(merged.foo).to.equal('not-bar'); + }); + }); });