export default function deepMerge(objA, objB) {
if (Array.isArray(objA) && Array.isArray(objB)) {
return [...objA.map(deepCopy), ...objB.map(deepCopy)];
}
const result = {};
const keysA = Object.keys(objA);
const keysB = Object.keys(objB);
const allKeys = new Set([...keysA, ...keysB]);
for (const key of allKeys) {
const valA = objA[key];
const valB = objB[key];
const inA = Object.prototype.hasOwnProperty.call(objA, key);
const inB = Object.prototype.hasOwnProperty.call(objB, key);
if (inA && !inB) {
result[key] = deepCopy(valA);
} else if (!inA && inB) {
result[key] = deepCopy(valB);
} else if (Array.isArray(valA) && Array.isArray(valB)) {
result[key] = [...valA, ...valB];
} else if (isPlainObject(valA) && isPlainObject(valB)) {
result[key] = deepMerge(valA, valB);
} else {
result[key] = deepCopy(valB);
}
}
return result;
}
function isPlainObject(value) {
if (value === null || typeof value !== 'object') {
return false;
}
const proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
function deepCopy(value) {
if (Array.isArray(value)) {
return value.map(deepCopy);
}
if (isPlainObject(value)) {
const copy = {};
for (const key of Object.keys(value)) {
copy[key] = deepCopy(value[key]);
}
return copy;
}
return value;
}