Skip to content

Instantly share code, notes, and snippets.

@ahonn
Last active September 25, 2019 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahonn/33ac42aa3046701cdaf78e5ea9537125 to your computer and use it in GitHub Desktop.
Save ahonn/33ac42aa3046701cdaf78e5ea9537125 to your computer and use it in GitHub Desktop.
implement object deep clone
function deepClone(source, hash = new WeakMap()) {
if (source === null || typeof source !== 'object') {
return source;
}
if (source instanceof Date) {
return new Date(source);
}
if (source instanceof RegExp) {
return new RegExp(source);
}
if (hash.has(source)) {
return hash.get(source);
}
const ins = new source.constructor();
hash.set(source, ins);
for (const key in source) {
if (source.hasOwnProperty(key)) {
ins[key] = deepClone(source[key], hash);
}
}
return ins;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment