5
5
const isObject = require ( './isObject' )
6
6
7
7
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
18
10
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 ( ) )
20
13
if ( obj instanceof RegExp ) return new RegExp ( obj )
21
14
if ( obj instanceof Map ) {
22
15
const newMap = new Map ( )
@@ -34,16 +27,17 @@ const cloneDeep = (obj, clones = new WeakMap()) => {
34
27
} )
35
28
return newSet
36
29
}
30
+ if ( Buffer . isBuffer ( obj ) ) return Buffer . from ( obj )
31
+ if ( ArrayBuffer . isView ( obj ) && ! ( obj instanceof DataView ) ) {
32
+ return new obj . constructor ( obj )
33
+ }
37
34
38
- const clonedObj = Array . isArray ( obj ) ? [ ] : { }
35
+ const clonedObj = Array . isArray ( obj ) ? [ ] : Object . create ( Object . getPrototypeOf ( obj ) )
39
36
clones . set ( obj , clonedObj )
37
+ Object . defineProperties ( clonedObj , Object . getOwnPropertyDescriptors ( obj ) )
40
38
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 )
47
41
}
48
42
49
43
return clonedObj
0 commit comments