Skip to content

Instantly share code, notes, and snippets.

@Aleksey-Danchin
Created May 20, 2020 12:38
Show Gist options
  • Save Aleksey-Danchin/a848bae84efbe0551dd7688b28e10551 to your computer and use it in GitHub Desktop.
Save Aleksey-Danchin/a848bae84efbe0551dd7688b28e10551 to your computer and use it in GitHub Desktop.
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