Created
February 2, 2022 14:26
-
-
Save gs-ysingh/83a86bb87c3423e152ed34b90ff31394 to your computer and use it in GitHub Desktop.
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(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