Skip to content

Commit

Permalink
fix: clonedeep source key if its an object
Browse files Browse the repository at this point in the history
  • Loading branch information
yurisldk committed Dec 5, 2022
1 parent f4be7ab commit 5529b78
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
15 changes: 15 additions & 0 deletions packages/mui-utils/src/deepmerge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,19 @@ describe('deepmerge', () => {
bar: 'test',
});
});

it('should deep clone source key object if target key does not exist', () => {
const foo = { foo: { baz: 'test' } };
const bar = {};

const result = deepmerge(bar, foo);

expect(result).to.deep.equal({ foo: { baz: 'test' } });

// @ts-ignore
result.foo.baz = 'new test';

expect(result).to.deep.equal({ foo: { baz: 'new test' } });
expect(foo).to.deep.equal({ foo: { baz: 'test' } });
});
});
6 changes: 5 additions & 1 deletion packages/mui-utils/src/deepmerge.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { cloneDeep } from 'lodash';

export function isPlainObject(item: unknown): item is Record<keyof any, unknown> {
return item !== null && typeof item === 'object' && item.constructor === Object;
}
Expand All @@ -24,7 +26,9 @@ export default function deepmerge<T>(
// Since `output` is a clone of `target` and we have narrowed `target` in this block we can cast to the same type.
(output as Record<keyof any, unknown>)[key] = deepmerge(target[key], source[key], options);
} else {
(output as Record<keyof any, unknown>)[key] = source[key];
(output as Record<keyof any, unknown>)[key] = isPlainObject(source[key])
? cloneDeep(source[key])
: source[key];
}
});
}
Expand Down

0 comments on commit 5529b78

Please sign in to comment.