Skip to content

Commit

Permalink
📖 DOC: Add cloneDeep() function for deep cloning objects and arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
Shaban-Eissa committed Jun 7, 2024
1 parent 68edb5d commit 63e6a97
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions 63.create-cloneDeep.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,28 @@ function cloneDeep(data) {
}
```

#

### Explanation
Let's break down the selected code:

1. `const cachedResult = new WeakMap();` This line creates a new WeakMap that will be used to store cloned objects. This is used to handle circular references in the object being cloned.

2. `function cloneDeep(data) {...}` This is the main function that performs a deep clone of an object. It takes an object as input and returns a new object that is a deep copy of the input.

3. Inside `cloneDeep` the function first checks if the input is null or not an object. If it is, the input is returned as is.

4. Then, it checks if the input is already in the `cachedResult` WeakMap. If it is, the function returns the cloned object from the WeakMap instead of cloning it again. This is how the function handles circular references.

5. If the input is not in the `cachedResult` WeakMap, the function creates a new object or array to be the clone, depending on whether the input is an array or not.

6. The function then stores the input and its clone in the `cachedResult` WeakMap.

7. The function gets all the own property names and symbols of the input, and for each one, it sets the corresponding property of the clone to be a deep clone of the property of the input. This is done recursively using `cloneDeep`

8. Finally, the function returns the clone.


#

### Reference
Expand Down

0 comments on commit 63e6a97

Please sign in to comment.