refactor deepCopy & deepMerge
This commit is contained in:
parent
2086f10af4
commit
279149b8b8
25
messaging.js
25
messaging.js
|
@ -186,27 +186,24 @@ function debounce(fn, delay, ...args) {
|
||||||
|
|
||||||
|
|
||||||
function deepCopy(obj) {
|
function deepCopy(obj) {
|
||||||
if (!obj || typeof obj != 'object') {
|
return obj !== null && obj !== undefined && typeof obj == 'object'
|
||||||
return obj;
|
? deepMerge(typeof obj.slice == 'function' ? [] : {}, obj)
|
||||||
} else {
|
: obj;
|
||||||
const emptyCopy = Object.create(Object.getPrototypeOf(obj));
|
|
||||||
return deepMerge(emptyCopy, obj);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
function deepMerge(target, ...args) {
|
function deepMerge(target, ...args) {
|
||||||
|
const isArray = typeof target.slice == 'function';
|
||||||
for (const obj of args) {
|
for (const obj of args) {
|
||||||
|
if (isArray && obj !== null && obj !== undefined) {
|
||||||
|
for (const element of obj) {
|
||||||
|
target.push(deepCopy(element));
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
for (const k in obj) {
|
for (const k in obj) {
|
||||||
const value = obj[k];
|
const value = obj[k];
|
||||||
if (!value || typeof value != 'object') {
|
if (k in target && typeof value == 'object' && value !== null) {
|
||||||
target[k] = value;
|
|
||||||
} else if (typeof value.slice == 'function') {
|
|
||||||
const arrayCopy = target[k] = target[k] || [];
|
|
||||||
for (const element of value) {
|
|
||||||
arrayCopy.push(deepCopy(element));
|
|
||||||
}
|
|
||||||
} else if (k in target) {
|
|
||||||
deepMerge(target[k], value);
|
deepMerge(target[k], value);
|
||||||
} else {
|
} else {
|
||||||
target[k] = deepCopy(value);
|
target[k] = deepCopy(value);
|
||||||
|
|
Loading…
Reference in New Issue
Block a user