前端深拷贝
前端深拷贝非常优质的函数,包含函数、循环引用,Set、Map、Date、自定义构造函数等处理
function deepClone(obj: any, hash = new WeakMap()): any {
if (Object(obj) !== obj) return obj // 处理基础类型
if (hash.has(obj)) return hash.get(obj) // 处理循环引用
const result = Array.isArray(obj)
? []
: obj instanceof Set
? new Set(obj)
: obj instanceof Map
? new Map(Array.from(obj, ([key, val]) => [key, deepClone(val, hash)]))
: obj instanceof Date
? new Date(obj.getTime())
: obj instanceof RegExp
? new RegExp(obj.source, obj.flags)
: typeof obj === 'function'
? obj
: obj.constructor
? new obj.constructor()
: Object.create(null)
hash.set(obj, result)
return Object.assign(result, ...Object.keys(obj).map((key) => ({ [key]: deepClone(obj[key], hash) })))
}
单元测试
it('深拷贝测试', () => {
function deepClone(obj: any, hash = new WeakMap()): any {
if (Object(obj) !== obj) return obj // 处理基础类型
if (hash.has(obj)) return hash.get(obj) // 处理循环引用
const result = Array.isArray(obj)
? []
: obj instanceof Set
? new Set(obj)
: obj instanceof Map
? new Map(Array.from(obj, ([key, val]) => [key, deepClone(val, hash)]))
: obj instanceof Date
? new Date(obj.getTime())
: obj instanceof RegExp
? new RegExp(obj.source, obj.flags)
: typeof obj === 'function'
? obj
: obj.constructor
? new obj.constructor()
: Object.create(null)
hash.set(obj, result)
return Object.assign(result, ...Object.keys(obj).map((key) => ({ [key]: deepClone(obj[key], hash) })))
}
const obj = {
date: new Date(1716433194530),
regex: /test/i,
map: new Map([['key', { nested: 'value' }]]),
set: new Set([1, 2, 3]),
func: function () {
console.log('Hello!')
},
nested: { a: 1, b: [2, 3] },
n: null,
un: undefined
}
const clone = deepClone(obj)
expect(clone).toEqual(obj)
expect(clone).not.toBe(obj)
expect(clone.nested).not.toBe(obj.nested)
expect(clone.map.get('key')).not.toBe(obj.map.get('key'))
expect(clone.date.getTime()).toBe(obj.date.getTime())
expect(clone.regex.source).toBe(obj.regex.source)
expect(clone.regex.flags).toBe(obj.regex.flags)
expect(Array.from(clone.set)).toEqual(Array.from(obj.set))
expect(clone.func.toString()).toBe(obj.func.toString())
expect(clone.n).toBe(obj.n)
expect(clone.un).toBe(obj.un)
})
点个收藏点个赞再走呀
点个收藏点个赞再走呀
点个收藏点个赞再走呀
点个收藏点个赞再走呀
点个收藏点个赞再走呀
点个收藏点个赞再走呀
点个收藏点个赞再走呀