Last active
December 31, 2017 05:50
-
-
Save varun93/6a70762d8d3565c825d7604e68b0af52 to your computer and use it in GitHub Desktop.
Snippet to clone a javascript Object for learning purposes only. This is based on Rick Waldron's implementation.
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
const clone = (deepCopy = false, source) => { | |
if (Array.isArray(source)) { | |
let array = []; | |
source.forEach((element, index) => { | |
if (typeof element == "object") { | |
array[index] = clone(deepCopy, element); | |
} else { | |
array[index] = element; | |
} | |
}); | |
return array; | |
} | |
return Object.keys(source).reduce((acc, key) => { | |
const valueToBeCopied = source[key]; | |
if (typeof valueToBeCopied == "object") { | |
valueToBeCopied = clone(deepCopy, valueToBeCopied); | |
if (deepCopy) { | |
const descriptor = Object.getOwnPropertyDescriptor(source, key); | |
descriptor.value = valueToBeCopied; | |
valueToBeCopied = descriptor; | |
} | |
} | |
acc[key] = valueToBeCopied; | |
return acc; | |
}, {}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment