Last active
April 11, 2022 10:11
-
-
Save ZacharyL2/f0af10ac6dc6f5fc7016366650d3da59 to your computer and use it in GitHub Desktop.
Deep copy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const deepClone = (obj, map = new WeakMap()) => { | |
if (obj instanceof Date) return new Date(obj); | |
if (obj instanceof RegExp) return new RegExp(obj); | |
if (map.has(obj)) { | |
return map.get(obj); | |
} | |
const allDesc = Object.getOwnPropertyDescriptors(obj); | |
const cloneObj = Object.create(Object.getPrototypeOf(obj), allDesc); | |
map.set(obj, cloneObj); | |
for (const key of Reflect.ownKeys(obj)) { | |
const value = obj[key]; | |
cloneObj[key] = | |
value instanceof Object && typeof value !== 'function' | |
? deepClone(value, map) | |
: value; | |
} | |
return cloneObj; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment