Created
September 4, 2018 11:59
-
-
Save fed135/057bc0387c56d0ca00ee1ca4a17a1a98 to your computer and use it in GitHub Desktop.
Deep Clone (Time Limit 1h)
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
function clone(target, options = {}) { | |
options = Object.assign({ omitTypes: [], maxDepth: 10 }, options); | |
const parents = []; | |
const copiedParents = []; | |
const complexTypes = [Boolean, Number, String, Date, Error, Map, Set, RegExp]; | |
const skippedTypes = [Symbol, Function]; | |
function cloneLayer(obj, layer = 0) { | |
// Simple/complex types | |
if (obj === null) return null; | |
if (obj === undefined) return undefined; | |
if (Array.isArray(obj)) return Array.from(obj); | |
if (complexTypes.includes(obj.constructor)) return new obj.constructor(obj); | |
if (skippedTypes.includes(obj.constructor)) return obj; | |
// Recursive associations | |
for (let i = 0; i < parents.length; i++) { | |
if (Object.is(parents[i], obj)) return copiedParents[i]; | |
} | |
if (layer >= options.maxDepth) return {}; | |
// Object types | |
parents.push(obj); | |
const copy = {}; | |
copiedParents.push(copy); | |
for (let i in obj) { | |
if (obj.hasOwnProperty(i)) { | |
if (obj[i] !== null && !options.omitTypes.includes(obj[i].constructor)) { | |
copy[i] = cloneLayer(obj[i], layer + 1); | |
} | |
} | |
} | |
return copy; | |
} | |
return cloneLayer(target); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment