Created
July 7, 2023 11:10
-
-
Save SK-CSE/77ecb309e853c5cb84b0382ae975dabd to your computer and use it in GitHub Desktop.
Deep Clone million of nested object without throwing call stack exceeded
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(obj) { | |
const stack = [{ source: obj, target: {} }]; | |
const map = new WeakMap(); | |
while (stack.length > 0) { | |
const { source, target } = stack.pop(); | |
map.set(source, target); | |
for (let key in source) { | |
if (source.hasOwnProperty(key)) { | |
const value = source[key]; | |
if (typeof value === 'object' && value !== null) { | |
if (map.has(value)) { | |
target[key] = map.get(value); | |
} else { | |
const clonedObject = Array.isArray(value) ? [] : {}; | |
stack.push({ source: value, target: clonedObject }); | |
map.set(value, clonedObject); | |
target[key] = clonedObject; | |
} | |
} else { | |
target[key] = value; | |
} | |
} | |
} | |
} | |
return map.get(obj); | |
} | |
/// regular deepclone code below | |
function cloneDeep(value) { | |
if (typeof value !== 'object' || value === null) { | |
return value; | |
} | |
let clonedValue; | |
if (Array.isArray(value)) { | |
clonedValue = []; | |
for (let i = 0; i < value.length; i++) { | |
clonedValue[i] = cloneDeep(value[i]); | |
} | |
} else { | |
clonedValue = {}; | |
for (let key in value) { | |
if (value.hasOwnProperty(key)) { | |
clonedValue[key] = cloneDeep(value[key]); | |
} | |
} | |
} | |
return clonedValue; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment