/**
* @description: 深拷贝
* @param { any } source 数据源
* @param { Map } cache 缓存(不传,有默认值)
* @return { any } 复制值
*/
function deepCopy(source, cache = new Map()) {
if (source instanceof Object) {
// 函数
if (typeof source === 'function') {
return source;
}
// 数组
if (Array.isArray(source)) {
const arr = [];
cache.set(source, arr);
for (let i = 0; i < source.length; i++) {
setValue(source, arr, i);
}
return arr;
}
// 对象
const obj = {};
cache.set(source, obj);
for (const key in source) {
if (Object.hasOwnProperty.call(source, key)) {
setValue(source, obj, key);
}
}
// Symbol
const symbols = Object.getOwnPropertySymbols(source);
for (const value of symbols) {
setValue(source, obj, value);
}
return obj;
}
return source;
// 设置值
function setValue(source, target, key) {
if (source[key] instanceof Object) {
target[key] = cache.has(source[key]) ? cache.get(source[key]) : deepCopy(source[key], cache);
} else {
target[key] = source[key];
}
}
}