Skip to content

Commit

Permalink
fix(deepmerge): should not mutate the input object [#76] (#77)
Browse files Browse the repository at this point in the history
  • Loading branch information
evenchange4 committed Oct 6, 2020
1 parent f710c87 commit e1508c6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
14 changes: 12 additions & 2 deletions packages/utils/src/__tests__/deepmerge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ describe('deepmerge', () => {
const mergeObject = { a: { b: 2 } };
const result = deepmerge({ a: { c: 3 }, b: 2, c: 3 }, mergeObject);

expect(result).toMatchObject({ a: { b: 2, c: 3 }, b: 2, c: 3 });
expect(result).toEqual({ a: { b: 2, c: 3 }, b: 2, c: 3 });
});

test('should work with empty object', () => {
Expand All @@ -27,7 +27,7 @@ describe('deepmerge', () => {
);
expect(result).toEqual({
a: { b: { c: { d: 'change string' } } },
b: { a: { d: true } },
b: { a: { d: true } }
});
});

Expand Down Expand Up @@ -78,4 +78,14 @@ describe('deepmerge', () => {
expect(result.a.b.b.c).toBe(true);
});
});

test('should not mutate the input object', () => {
const origin = { a: { c: 3 }, b: 2, c: 3 };
const target = { a: { b: 2 } };
const result = deepmerge(origin, target);

expect(result).toEqual({ a: { b: 2, c: 3 }, b: 2, c: 3 });
expect(origin).toEqual({ a: { c: 3 }, b: 2, c: 3 });
expect(target).toEqual({ a: { b: 2 } });
});
});
13 changes: 7 additions & 6 deletions packages/utils/src/deepmerge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,23 @@ function mergeTwoObject(origin: any, target: any) {
if (target === null || typeof target === 'undefined') {
return origin;
}
const result = { ...origin };

Object.keys(target).forEach((key) => {
const originValue = origin[key];
Object.keys(target).forEach(key => {
const originValue = result[key];
const targetValue = target[key];
if (Array.isArray(originValue) || Array.isArray(targetValue)) {
origin[key] = targetValue;
result[key] = targetValue;
} else if (
typeof originValue === 'object' &&
typeof targetValue === 'object'
) {
origin[key] = mergeTwoObject(originValue, targetValue);
result[key] = mergeTwoObject(originValue, targetValue);
} else {
origin[key] = targetValue;
result[key] = targetValue;
}
});
return origin;
return result;
}

export function deepmerge(...args: any[]) {
Expand Down

0 comments on commit e1508c6

Please sign in to comment.