Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[utils] Handle circular reference of objects in deepMerge #38647

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -11,6 +11,21 @@ describe('deepmerge', () => {
expect({}).not.to.have.property('isAdmin');
});

it('should handle circular references by avoiding infinite recursion during deep cloning', () => {
const circularObj = {
prop1: 'value1',
};
// @ts-ignore
circularObj.circularRef = circularObj;

const result = deepmerge({}, circularObj);

expect(result).to.deep.equal({
prop1: 'value1',
circularRef: { prop1: 'value1', circularRef: { prop1: 'value1' } },
});
});

// https://github.com/mui/material-ui/issues/20095
it('should not merge HTML elements', () => {
const element = document.createElement('div');
Expand Down
9 changes: 7 additions & 2 deletions packages/mui-utils/src/deepmerge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,20 @@ export interface DeepmergeOptions {
clone?: boolean;
}

function deepClone<T>(source: T): T | Record<keyof any, unknown> {
function deepClone<T>(source: T, visited = new Set()): T | Record<keyof any, unknown> {
if (!isPlainObject(source)) {
return source;
}

const output: Record<keyof any, unknown> = {};

Object.keys(source).forEach((key) => {
output[key] = deepClone(source[key]);
if (!visited.has(source[key])) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I get that this fix is not really cloning circular objects, but I can't think of a better way to handle circular objects

if (typeof source[key] === 'object') {
visited.add(source[key]);
}
output[key] = deepClone(source[key], visited);
}
});

return output;
Expand Down