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 20, 2022
1 parent 9e140a7 commit a9a5287
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
15 changes: 15 additions & 0 deletions packages/mui-utils/src/deepmerge.test.ts
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' } });
});
});
18 changes: 18 additions & 0 deletions packages/mui-utils/src/deepmerge.ts
Expand Up @@ -6,6 +6,20 @@ export interface DeepmergeOptions {
clone?: boolean;
}

function deepClone<T>(source: T): 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]);
});

return output;
}

export default function deepmerge<T>(
target: T,
source: unknown,
Expand All @@ -23,6 +37,10 @@ export default function deepmerge<T>(
if (isPlainObject(source[key]) && key in target && isPlainObject(target[key])) {
// 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 if (options.clone) {
(output as Record<keyof any, unknown>)[key] = isPlainObject(source[key])
? deepClone(source[key])
: source[key];
} else {
(output as Record<keyof any, unknown>)[key] = source[key];
}
Expand Down

0 comments on commit a9a5287

Please sign in to comment.