Skip to content

Commit

Permalink
Update deepClone.md
Browse files Browse the repository at this point in the history
  • Loading branch information
Chalarangelo committed Sep 4, 2020
1 parent e24194c commit de38320
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions snippets/deepClone.md
Expand Up @@ -3,12 +3,14 @@ title: deepClone
tags: object,recursion,intermediate
---

Creates a deep clone of an object.
Creates a deep clone of an object.
Clones primitives, arrays and objects, excluding class instances.

Use recursion.
Check if the passed object is `null` and, if so, return `null`.
Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original.
Use `Object.keys()` and `Array.prototype.forEach()` to determine which key-value pairs need to be deep cloned.
If the object is an `Array`, set the `clone`'s `length` to that of the original and use `Array.from(clone)` to create a clone.

```js
const deepClone = obj => {
Expand All @@ -17,15 +19,15 @@ const deepClone = obj => {
Object.keys(clone).forEach(
key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
);
return Array.isArray(obj) && obj.length
? (clone.length = obj.length) && Array.from(clone)
: Array.isArray(obj)
? Array.from(obj)
: clone;
if (Array.isArray(obj)) {
clone.length = obj.length;
return Array.from(clone);
}
return clone;
};
```

```js
const a = { foo: 'bar', obj: { a: 1, b: 2 } };
const b = deepClone(a); // a !== b, a.obj !== b.obj
```
```

0 comments on commit de38320

Please sign in to comment.