Skip to content

Commit

Permalink
feat(core): mergeDeep supports array
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Apr 9, 2023
1 parent 7603b92 commit 28ae639
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
15 changes: 11 additions & 4 deletions packages/core/src/utils/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,18 +47,25 @@ export function isObject(item: any): item is Record<string, any> {
return (item && typeof item === 'object' && !Array.isArray(item))
}

export function mergeDeep<T>(original: T, patch: DeepPartial<T>): T {
/**
* Deep merge two objects
*/
export function mergeDeep<T>(original: T, patch: DeepPartial<T>, mergeArray = false): T {
const o = original as any
const p = patch as any

if (Array.isArray(o))
return [...p] as any
if (Array.isArray(p)) {
if (mergeArray && Array.isArray(p))
return [...o, ...p] as any
else
return [...p] as any
}

const output = { ...o }
if (isObject(o) && isObject(p)) {
Object.keys(p).forEach((key) => {
if (((isObject(o[key]) && isObject(p[key])) || (Array.isArray(o[key]) && Array.isArray(p[key]))))
output[key] = mergeDeep(o[key], p[key])
output[key] = mergeDeep(o[key], p[key], mergeArray)
else
Object.assign(output, { [key]: p[key] })
})
Expand Down
20 changes: 20 additions & 0 deletions test/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,26 @@ it('mergeDeep', () => {
"foo": true,
}
`)

expect(mergeDeep<any>({
foo: true,
bar: 1,
arr: [1],
}, {
bar: {},
arr: [2],
} as any,
true))
.toMatchInlineSnapshot(`
{
"arr": [
1,
2,
],
"bar": {},
"foo": true,
}
`)
})

it('getComponents', () => {
Expand Down

0 comments on commit 28ae639

Please sign in to comment.