Created
July 12, 2018 13:34
-
-
Save esakal/71ad4da0703087b43e2e55daa713ce60 to your computer and use it in GitHub Desktop.
deep clone with customizer
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 deepClone(source, customizer){ | |
const _deepClone = function (source, customizer, sourcePath) { | |
// If the source isn't an Object or Array, throw an error. | |
if ( !(source instanceof Object) || source instanceof Date || source instanceof String) { | |
throw new Error('Only Objects or Arrays are supported.'); | |
} | |
// Set the target data type before copying. | |
var target = source instanceof Array ? [] : {}; | |
for (let prop in source){ | |
// Make sure the property isn't on the protoype | |
if ( source instanceof Object && !(source instanceof Array) && !(source.hasOwnProperty(prop)) ) { | |
continue; | |
} | |
const propValue = source[prop]; | |
let propPath = null; | |
if (sourcePath) { | |
propPath = `${sourcePath}${Array.isArray(source) ? `[${prop}]` : `.${prop}`}`; | |
} else { | |
propPath = Array.isArray(source) ? `[${prop}]` : prop; | |
} | |
// If the current property is an Array or Object, recursively clone it, else copy it's value | |
if ( propValue instanceof Object && !(propValue instanceof Date) && !(propValue instanceof String) ) { | |
target[prop] = _deepClone(propValue, customizer, propPath) | |
} else { | |
if (customizer) { | |
target[prop] = customizer(propValue, propPath); | |
} else { | |
target[prop] = propValue; | |
} | |
} | |
} | |
return target; | |
} | |
return _deepClone(source, customizer, ""); | |
} | |
export default deepClone; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment