Skip to content

Commit

Permalink
fix: deepCopy should never merge arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
BobbieGoede committed Sep 15, 2024
1 parent df4b09f commit 05b2353
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions packages/shared/src/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,22 @@ export function deepCopy(src: any, des: any): void {
while (stack.length) {
const { src, des } = stack.pop()!

// using `Object.keys` which skips prototype properties
Object.keys(src).forEach(key => {
// if src[key] is an object/array, set des[key]
// to empty object/array to prevent setting by reference
if (isObject(src[key]) && !isObject(des[key])) {
des[key] = Array.isArray(src[key]) ? [] : {}
}

if (isObject(des[key]) && isObject(src[key])) {
// src[key] and des[key] are both objects, merge them
stack.push({ src: src[key], des: des[key] })
} else {
if (isNotObjectOrIsArray(des[key]) || isNotObjectOrIsArray(src[key])) {
// replace with src[key] when:
// src[key] or des[key] is not an object, or
// src[key] or des[key] is an array
des[key] = src[key]
} else {
// src[key] and des[key] are both objects, merge them
stack.push({ src: src[key], des: des[key] })
}
})
}
Expand Down

0 comments on commit 05b2353

Please sign in to comment.