From 63e6a97f48da14d94dbc00d2e19245b750f4ee57 Mon Sep 17 00:00:00 2001 From: Shaban-Eissa Date: Fri, 7 Jun 2024 15:24:40 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=96=20DOC:=20Add=20cloneDeep()=20funct?= =?UTF-8?q?ion=20for=20deep=20cloning=20objects=20and=20arrays?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 63.create-cloneDeep.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/63.create-cloneDeep.md b/63.create-cloneDeep.md index 5dbcf08..b13e328 100644 --- a/63.create-cloneDeep.md +++ b/63.create-cloneDeep.md @@ -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