Skip to content

Instantly share code, notes, and snippets.

@disgusting-dev
Created March 16, 2021 21:00
Show Gist options
  • Save disgusting-dev/4a00dbdd2c8435d15df25c1b12411083 to your computer and use it in GitHub Desktop.
Save disgusting-dev/4a00dbdd2c8435d15df25c1b12411083 to your computer and use it in GitHub Desktop.
function isObject(value) {
return typeof value === 'object';
}
function deepCopy(value, hash = new Map()) {
let newVal;
if (hash.has(value)) {
return hash.get(value);
}
if (Array.isArray(value)) {
hash.set(value, newVal);
newVal = value.map(item => {
return deepCopy(item, hash);
});
} else if (value && isObject(value)) {
newVal = {};
Object.keys(value).forEach(key => {
if (isObject(value[key])) {
hash.set(value, newVal);
newVal[key] = deepCopy(value[key], hash);
} else {
newVal[key] = value[key];
}
});
} else {
newVal = value;
}
return newVal;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment