Add deepClone.md

This commit is contained in:
Angelos Chalaris
2018-01-23 20:48:46 +02:00
parent 18171a093c
commit 2883a77110
2 changed files with 27 additions and 1 deletions

25
snippets/deepClone.md Normal file
View File

@ -0,0 +1,25 @@
### deepClone
Creates a deep clone of an object.
Use recursion.
Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original.
Use `Object.keys()` and `Array.forEach()` to determine which key-value pairs need to be deep cloned.
```js
const deepClone = obj => {
let clone = Object.assign({}, obj);
Object.keys(clone).forEach(
key =>
(clone[key] = typeof obj[key] === 'object'
? deepClone(obj[key])
: obj[key])
);
return clone;
};
```
```js
const a = { foo: 'bar', obj: { a: 1, b: 2 } };
const b = deepClone(a); // a !== b, a.obj !== b.obj
```

View File

@ -27,6 +27,7 @@ createEventHub:browser,event,advanced
currentURL:browser,url
curry:function,recursion
decapitalize:string,array
deepClone:object,recursion
deepFlatten:array,recursion
defaults:object
defer:function
@ -125,7 +126,7 @@ mapObject:array,object
mapValues:object,function
mask:string,utility,regexp
matches:object,type
matchesWith:object,type,function
matchesWith:object,type,function
maxBy:math,array,function
maxN:array,math
median:math,array