Skip to content

Instantly share code, notes, and snippets.

@pratheeshrussell
Created May 18, 2023 04:49
Show Gist options
  • Save pratheeshrussell/3136a49f2e5af3986c49ff6dac7e8fce to your computer and use it in GitHub Desktop.
Save pratheeshrussell/3136a49f2e5af3986c49ff6dac7e8fce to your computer and use it in GitHub Desktop.
A function to deepcopy in js
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