Skip to content

Instantly share code, notes, and snippets.

@anderjs
Created August 8, 2019 21:50
Show Gist options
  • Save anderjs/3f959783a7f2bac382250b4cf1fa8e99 to your computer and use it in GitHub Desktop.
Save anderjs/3f959783a7f2bac382250b4cf1fa8e99 to your computer and use it in GitHub Desktop.
A deep cloning using JavaScript.
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