Last active
September 25, 2019 10:09
-
-
Save ahonn/33ac42aa3046701cdaf78e5ea9537125 to your computer and use it in GitHub Desktop.
implement object deep clone
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
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