Skip to content

Commit 11f8638

Browse files
committed
deepclone copy objects with prototype
1 parent 58c0e07 commit 11f8638

File tree

1 file changed

+12
-18
lines changed

1 file changed

+12
-18
lines changed

src/cloneDeep.js

+12-18
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,11 @@
55
const isObject = require('./isObject')
66

77
const cloneDeep = (obj, clones = new WeakMap()) => {
8-
if (obj instanceof Function) {
9-
return {}
10-
}
11-
if (!isObject(obj)) {
12-
return obj
13-
}
14-
15-
if (clones.has(obj)) {
16-
return clones.get(obj)
17-
}
8+
if (obj instanceof Function) return {}
9+
if (!isObject(obj)) return obj
1810

19-
if (obj instanceof Date) return new Date(obj)
11+
if (clones.has(obj)) return clones.get(obj)
12+
if (obj instanceof Date) return new Date(obj.getTime())
2013
if (obj instanceof RegExp) return new RegExp(obj)
2114
if (obj instanceof Map) {
2215
const newMap = new Map()
@@ -34,16 +27,17 @@ const cloneDeep = (obj, clones = new WeakMap()) => {
3427
})
3528
return newSet
3629
}
30+
if (Buffer.isBuffer(obj)) return Buffer.from(obj)
31+
if (ArrayBuffer.isView(obj) && !(obj instanceof DataView)) {
32+
return new obj.constructor(obj)
33+
}
3734

38-
const clonedObj = Array.isArray(obj) ? [] : {}
35+
const clonedObj = Array.isArray(obj) ? [] : Object.create(Object.getPrototypeOf(obj))
3936
clones.set(obj, clonedObj)
37+
Object.defineProperties(clonedObj, Object.getOwnPropertyDescriptors(obj))
4038

41-
if (Array.isArray(obj)) return obj.map(item => cloneDeep(item, clones))
42-
43-
for (const key in obj) {
44-
if (obj.hasOwnProperty(key)) {
45-
clonedObj[key] = cloneDeep(obj[key], clones)
46-
}
39+
for (const key of Object.keys(clonedObj)) {
40+
clonedObj[key] = cloneDeep(clonedObj[key], clones)
4741
}
4842

4943
return clonedObj

0 commit comments

Comments
 (0)