Skip to content

Instantly share code, notes, and snippets.

@esakal
Created July 12, 2018 13:34
Show Gist options
  • Save esakal/71ad4da0703087b43e2e55daa713ce60 to your computer and use it in GitHub Desktop.
Save esakal/71ad4da0703087b43e2e55daa713ce60 to your computer and use it in GitHub Desktop.
deep clone with customizer
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