function getEmpty(o) {
if (Object.prototype.toString.call(o) === "[object Object]") {
return {};
}
if (Object.prototype.toString.call(o) === "[object Array]") {
return [];
}
return o;
}
/*只处理对象和数组,如果不是直接返回原对象 对function/set/map/symbol等不做处理*/
function deepCopyDFS(origin, map = new Map()) {
var _obj = getEmpty(origin);
if (_obj !== origin) {
if (map.get(origin)) {
return map.get(origin);
}
map.set(origin, _obj);
for (let key in origin) {
_obj[key] = deepCopyDFS(origin[key], map);
}
}
return _obj;
}
function deepCopyBFS(origin) {
var queue = [];
var map = new Map();
var target = getEmpty(origin);
if (target !== origin) {
queue.push([origin, target]);
map.set(origin, target);
}
while (queue.length) {
var [ori, tar] = queue.shift();
for (let key in ori) {
if (map.get(ori[key])) {
tar[key] = map.get(ori[key]);
} else {
tar[key] = getEmpty(ori[key]);
if (tar[key] !== ori[key]) {
queue.push([ori[key], tar[key]]);
map.set(ori[key], tar[key]);
}
}
}
}
return target;
}
// test
[deepCopyBFS, deepCopyDFS].forEach((deepCopy) => {
console.log(deepCopy({ a: 1 }));
console.log(deepCopy([1, 2, { a: [3, 4] }]));
console.log(
deepCopy(function () {
return 1;
})
);
console.log(
deepCopy({
x: function () {
return "x";
},
val: 3,
arr: [1, { test: 1 }],
})
);
let circle = {};
circle.child = circle;
console.log(deepCopy(circle));
});
网友评论