Skip to content

Instantly share code, notes, and snippets.

@peterver
Last active September 16, 2016 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterver/478401d891d26398b8d11ef30147c154 to your computer and use it in GitHub Desktop.
Save peterver/478401d891d26398b8d11ef30147c154 to your computer and use it in GitHub Desktop.
recursive copy / deep clone using lodash ( fixes issue with lodash cloneDeep on older browsers )
function copy (cursor) {
// Array
if (_.isArray(cursor)) {
return cursor.reduce((cursor_acc, cursor_value) => {
cursor_acc.push(copy(cursor_value));
return cursor_acc;
}, []);
}
// Object
if (_.isObject(cursor)) {
return (cursor.hasOwnProperty('clone') && _.isFunction(cursor.clone))
? cursor.clone()
: Object.keys(cursor).reduce((cursor_acc, cursor_key) => {
cursor_acc[cursor_key] = copy(cursor[cursor_key]);
return cursor_acc;
}, {});
}
if (_.isElement(cursor)) return cursor.cloneNode(true);
if (_.isRegExp(cursor)) return new RegExp(cursor);
if (_.isDate(cursor)) return new Date(cursor);
return cursor;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment