原生实现深度拷贝函数
function typeIs(data) {
if (!data) return typeof data
return data.constructor.name
}
function deepClone (data,cache = new WeakMap()) {
if (!data || typeof data !== 'object' || typeIs(data) === 'Date' || typeIs(data) === 'RegExp') return data
if (cache.get(data)) {
return cache.get(data)
}
if (typeIs(data) === 'Set') {
let temp = new Set()
cache.set(data,temp)
for (let v of data) {
temp.add(deepClone(v,cache))
}
return temp
}
if (typeIs(data) === 'Map') {
let temp = new Map()
cache.set(data,temp)
for (let [key,v] of data) {
temp.set(key,deepClone(v,cache))
}
return temp
}
let obj = Array.isArray(data) ? [] : {}
cache.set(data,obj)
for (let key of Reflect.ownKeys(data)) {
let v = data[key]
if (Array.isArray(data) && key === 'length') continue;
obj[key] = deepClone(v,cache)
}
return obj
}