Update snippet, add extra tests

This commit is contained in:
Angelos Chalaris
2019-09-28 13:35:11 +03:00
parent 6c00c38a61
commit f859b78b7d
7 changed files with 46 additions and 44 deletions

View File

@ -6,23 +6,17 @@ tags: object,recursion,intermediate
Creates a deep clone of an object.
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.
```js
const deepClone = obj => {
let type = typeof obj;
let isAssignable = type === "function" || type === "object" && !!obj;
if (!isAssignable) {
return obj;
}
if (obj === null) return null;
let clone = Object.assign({}, obj);
Object.keys(clone).forEach(
key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
);
if (obj) {
Object.setPrototypeOf(clone, Object.getPrototypeOf(obj));
}
return Array.isArray(obj) && obj.length
? (clone.length = obj.length) && Array.from(clone)
: Array.isArray(obj)