Skip to content

Instantly share code, notes, and snippets.

@lac5
Last active June 17, 2024 15:03
Show Gist options
  • Save lac5/9cbac3af53178f5d581e939b96568677 to your computer and use it in GitHub Desktop.
Save lac5/9cbac3af53178f5d581e939b96568677 to your computer and use it in GitHub Desktop.
/**
* Clones an object and all sub-objects.
* `into = from;` -> `into = deepClone(from);` | `deepClone(from, into);`
* @param {Object} from Getter object.
* @param {Object} [into = {}] Setter object.
* @param {boolean} [noOverwrite = false] Flag to not overwrite non-null values in `into` if true.
* @return {Object} Returns `into`.
*/
export default function deepClone(from, into = {}, noOverwrite = false) {
let into = this == global ? Object.create(Object.getPrototypeOf(from)) : this;
for (let k of Object.keys(from)) {
if (from[k] && typeof from[k] === 'object') {
if (into[k] && typeof into[k] === 'object') {
deepClone(from[k], into[k]);
} else if (!noOverwrite || into[k] == null) {
into[k] = deepClone(from[k]);
}
} else if (!noOverwrite || into[k] == null) {
into[k] = from[k];
}
}
return into;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment