Skip to content

Instantly share code, notes, and snippets.

@gs-ysingh
Created February 2, 2022 14:26
Show Gist options
  • Save gs-ysingh/83a86bb87c3423e152ed34b90ff31394 to your computer and use it in GitHub Desktop.
Save gs-ysingh/83a86bb87c3423e152ed34b90ff31394 to your computer and use it in GitHub Desktop.
function deepCopy(source) {
return deepCopyHelper(source, {});
}
function deepCopyHelper(source, target) {
for(let key in source) {
const value = source[key];
if(typeof value !== "object") {
target[key] = value;
} else {
target[key] = Array.isArray(value) ? [] : {};
deepCopyHelper(source[key], target[key]);
}
}
return target;
}
// Input:
const c = {
n: [1, 2, 3],
l: ['a', 'b', 'c'],
o: { prop: 1 },
b: true,
x: 1,
};
console.log(deepCopy(c));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment