Created
July 26, 2012 22:08
-
-
Save amadeus/3184871 to your computer and use it in GitHub Desktop.
A nice and simple clone function.
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
var clone = function clone(src) { | |
var r, i, l, | |
mixin = function(dest, source, copyFunc) { | |
var name, s, i, empty = {}; | |
for(name in source){ | |
s = source[name]; | |
if(!(name in dest) || (dest[name] !== s && (!(name in empty) || empty[name] !== s))){ | |
dest[name] = copyFunc ? copyFunc(s) : s; | |
} | |
} | |
return dest; | |
}; | |
if(!src || typeof src != "object" || Object.prototype.toString.call(src) === "[object Function]") | |
return src; | |
if(src.nodeType && "cloneNode" in src) | |
return src.cloneNode(true); | |
if(src instanceof Date) | |
return new Date(src.getTime()); | |
if(src instanceof RegExp) | |
return new RegExp(src); | |
if(src && (src instanceof Array || typeof src == "array")){ | |
r = []; | |
for(i = 0, l = src.length; i < l; ++i){ | |
if(i in src) | |
r.push(clone(src[i])); | |
} | |
} | |
else | |
r = src.constructor ? new src.constructor() : {}; | |
return mixin(r, src, clone); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment