Created
August 8, 2019 21:50
-
-
Save anderjs/3f959783a7f2bac382250b4cf1fa8e99 to your computer and use it in GitHub Desktop.
A deep cloning using JavaScript.
This file contains hidden or 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
const { keys } = Object | |
const { isArray } = Array | |
/** | |
* @param {any} fragment | |
*/ | |
function applyCloningElement(fragment) { | |
if (typeof fragment !== 'object') { | |
return fragment | |
} | |
if (typeof fragment === 'object' && isArray(fragment)) { | |
const arrayOfFragments = [] | |
fragment.forEach((value) => { | |
arrayOfFragments.push(typeof value === 'object' ? clone(value) : value) | |
}) | |
return arrayOfFragments | |
} | |
return clone(fragment) | |
} | |
/** | |
* @module Clone | |
* @description | |
* Clone all properties from an object giving it to deepCopy. | |
*/ | |
/** | |
* @param {object} source | |
* @returns {object} | |
*/ | |
function clone (source) { | |
let clone = {} | |
/** | |
* If the @argument source is not an object, we return a simply object. | |
*/ | |
if (typeof source !== 'object') { | |
return {} | |
} | |
keys(source).forEach((key) => { | |
const currentKeyFragment = source[key] | |
clone[key] = applyCloningElement(currentKeyFragment) | |
}) | |
return clone | |
} | |
module.exports = clone |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment