Skip to content

Instantly share code, notes, and snippets.

@guillaumegarcia13
Forked from sstur/clone.js
Created February 20, 2018 16:36
Show Gist options
  • Save guillaumegarcia13/78305f07de61f515160415497bb703d6 to your computer and use it in GitHub Desktop.
Save guillaumegarcia13/78305f07de61f515160415497bb703d6 to your computer and use it in GitHub Desktop.
Deep-copy an object, similar to calling JSON.parse(JSON.stringify(obj)) but preserves dates and undefined
function clone(obj) {
if (Object(obj) !== obj) return obj;
if (typeof obj.toJSON == 'function') {
return obj.toJSON();
}
var type = toString.call(obj).slice(8, -1);
if (type in CLONE) {
return CLONE[type].call(obj, clone);
}
var copy = {};
var keys = Object.keys(obj);
for (var i = 0, len = keys.length; i < len; i++) {
var key = keys[i];
copy[key] = clone(obj[key]);
}
return copy;
}
var CLONE = {
'Array': function(clone) {
return Array.prototype.map.call(this, clone);
},
'Date': function() {
return new Date(this.valueOf());
},
'String': String.prototype.valueOf,
'Number': Number.prototype.valueOf,
'Boolean': Boolean.prototype.valueOf
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment