Skip to content

Instantly share code, notes, and snippets.

@varun93
Last active December 31, 2017 05:50
Show Gist options
  • Save varun93/6a70762d8d3565c825d7604e68b0af52 to your computer and use it in GitHub Desktop.
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.
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