Created
May 18, 2023 04:49
-
-
Save pratheeshrussell/3136a49f2e5af3986c49ff6dac7e8fce to your computer and use it in GitHub Desktop.
A function to deepcopy in js
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 deepCopy(obj) { | |
if (typeof obj !== 'object' || obj === null) { | |
return obj; | |
} | |
const isArray = Array.isArray(obj); | |
const copy = isArray ? [] : {}; | |
const stack = [{ source: obj, target: copy }]; | |
while (stack.length) { | |
const { source, target } = stack.pop(); | |
Object.keys(source).forEach(key => { | |
const value = source[key]; | |
if (typeof value === 'object' && value !== null) { | |
const isArray = Array.isArray(value); | |
const copyValue = isArray ? [] : {}; | |
target[key] = copyValue; | |
stack.push({ source: value, target: copyValue }); | |
} else { | |
target[key] = value; | |
} | |
}); | |
} | |
return copy; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment