Skip to content

Instantly share code, notes, and snippets.

@ZacharyL2
Last active April 11, 2022 10:11
Show Gist options
  • Save ZacharyL2/f0af10ac6dc6f5fc7016366650d3da59 to your computer and use it in GitHub Desktop.
Save ZacharyL2/f0af10ac6dc6f5fc7016366650d3da59 to your computer and use it in GitHub Desktop.
Deep copy
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