Skip to content

Commit

Permalink
fix: Create a simple merge object utility (#849)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexs-mparticle authored Mar 20, 2024
1 parent 12ac789 commit 1882032
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,10 @@ const isStringOrNumber = (value: any): boolean =>
const isEmpty = (value: Dictionary<any> | null | undefined): boolean =>
value == null || !(Object.keys(value) || value).length;

const mergeObjects = <T extends object>(...objects: T[]): T => {
return Object.assign({}, ...objects);
};

export {
createCookieString,
revertCookieString,
Expand Down Expand Up @@ -251,4 +255,5 @@ export {
isDataPlanSlug,
isEmpty,
isValidCustomFlagProperty,
mergeObjects,
};
47 changes: 47 additions & 0 deletions test/src/tests-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
isObject,
isStringOrNumber,
isValidCustomFlagProperty,
mergeObjects,
parseNumber,
parseStringOrNumber,
replaceApostrophesWithQuotes,
Expand Down Expand Up @@ -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<any>(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<any>(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<any>(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<any>(obj1, obj2);
merged.foo = 'not-bar';

expect(obj1.foo).to.equal('bar');
expect(merged.foo).to.equal('not-bar');
});
});
});

0 comments on commit 1882032

Please sign in to comment.