Created
November 13, 2019 09:16
-
-
Save intrnl/553786f04dadce370be6255b32c949a8 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
/** | |
* Deep clones an object or array | |
* @param {object|array} obj Object or array to clone | |
* @returns {object|array} Cloned object or array | |
*/ | |
function deepClone (obj) { | |
if (typeof obj !== 'object' || obj === null) return {}; | |
const res = Array.isArray(obj) ? [] : {}; | |
const queue = [{ base: res, current: obj }]; | |
while (queue.length) { | |
const { base, current } = queue.shift(); | |
const baseIsArray = Array.isArray(base); | |
for (const [key, value] of Object.entries(current)) { | |
const valueIsArray = Array.isArray(value); | |
const valueIsObject = typeof value === 'object' && value !== null; | |
if (baseIsArray) { | |
if (valueIsArray) { | |
const newBase = []; | |
base.push(newBase); | |
queue.push({ base: newBase, current: value }); | |
} else if (valueIsObject) { | |
const newBase = {}; | |
base.push(newBase); | |
queue.push({ base: newBase, current: value }); | |
} else { | |
base.push(value); | |
} | |
} else { | |
if (valueIsArray) { | |
const newBase = base[key] = []; | |
queue.push({ base: newBase, current: value }); | |
} else if (valueIsObject) { | |
const newBase = base[key] = {}; | |
queue.push({ base: newBase, current: value }); | |
} else { | |
base[key] = value; | |
} | |
} | |
} | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment