Last active
June 17, 2024 15:03
-
-
Save lac5/9cbac3af53178f5d581e939b96568677 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
/** | |
* 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