@@ -16,38 +16,20 @@ export function compareObjects(objectA: any, objectB: any, compareLength = false
16
16
return true ;
17
17
}
18
18
19
- /**
20
- * Create an immutable clone of an array or object
21
- * (c) 2019 Chris Ferdinandi, MIT License, https://gomakethings.com
22
- * @param {Array|Object } objectOrArray - the array or object to copy
23
- * @return {Array|Object } - the clone of the array or object
24
- */
25
- export function deepCopy ( objectOrArray : any | any [ ] ) : any | any [ ] {
26
- const cloneObj = ( ) => {
27
- const clone = { } ; // create new object
28
-
29
- // Loop through each item in the original, recursively copy it's value and add to the clone
30
- // eslint-disable-next-line no-restricted-syntax
31
- for ( const key in objectOrArray ) {
32
- if ( Object . prototype . hasOwnProperty . call ( objectOrArray , key ) ) {
33
- ( clone as any ) [ key ] = deepCopy ( objectOrArray [ key ] ) ;
34
- }
35
- }
36
- return clone ;
37
- } ;
38
-
39
- // Create an immutable copy of an array
40
- const cloneArr = ( ) => objectOrArray . map ( ( item : any ) => deepCopy ( item ) ) ;
19
+ export function deepCopy ( obj : any ) : any {
20
+ if ( typeof obj !== 'object' || obj === null ) {
21
+ return obj ;
22
+ }
41
23
42
- // Get object type
43
- const type = Object . prototype . toString . call ( objectOrArray ) . slice ( 8 , - 1 ) . toLowerCase ( ) ;
44
- if ( type === 'object' ) {
45
- return cloneObj ( ) ; // if it's an object
24
+ if ( Array . isArray ( obj ) ) {
25
+ return obj . map ( deepCopy ) ;
46
26
}
47
- if ( type === 'array' ) {
48
- return cloneArr ( ) ; // if it's an array
27
+
28
+ if ( typeof obj === 'function' ) {
29
+ return obj ;
49
30
}
50
- return objectOrArray ; // otherwise, return it as-is, could be primitive or else
31
+
32
+ return Object . fromEntries ( Object . entries ( obj ) . map ( ( [ key , value ] ) => [ key , deepCopy ( value ) ] ) ) ;
51
33
}
52
34
53
35
export function isDefined ( val : any ) {
0 commit comments