Created
May 20, 2020 12:38
-
-
Save Aleksey-Danchin/a848bae84efbe0551dd7688b28e10551 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 cloneDeep (obj) { | |
const pull = new Map | |
const clone = cloneDeepMaster(obj) | |
pull.clear() | |
return clone | |
function cloneDeepMaster (obj) { | |
if (typeof obj !== 'object' || obj === null) { | |
return obj | |
} | |
if (obj instanceof Array) { | |
const clone = [] | |
pull.set(obj, clone) | |
for (let i = 0; i < obj.length; i++) { | |
if (pull.has(obj[i])) { | |
clone.push(pull.get(obj[i])) | |
} | |
else { | |
clone.push(cloneDeepMaster(obj[i])) | |
} | |
} | |
return clone | |
} | |
else { | |
const clone = {} | |
pull.set(obj, clone) | |
for (const key in obj) { | |
if (pull.has(obj[key])) { | |
clone[key] = pull.get(obj[key]) | |
} | |
else { | |
clone[key] = cloneDeepMaster(obj[key]) | |
} | |
} | |
return clone | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment