Last active
September 16, 2016 10:51
-
-
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 )
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
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