Created
May 5, 2010 02:55
-
-
Save rentzsch/390325 to your computer and use it in GitHub Desktop.
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
function clone(obj) { | |
if (!obj || typeof obj !== 'object') { | |
return obj; | |
} | |
if (obj instanceof Date) { | |
return new Date(obj.getTime()); | |
} | |
var result, | |
propertyIndex, | |
propertyCount, | |
propertyKey, | |
propertyValue, | |
empty = {}; | |
if (obj instanceof Array || typeof obj === 'array') { | |
result = []; | |
for (; propertyIndex < propertyCount; propertyIndex++) { | |
result.push(clone(obj[propertyIndex])); | |
} | |
return result; | |
} else { | |
result = obj.constructor ? new obj.constructor() : {}; | |
for (propertyKey in obj) { | |
propertyValue = obj[propertyKey]; | |
if (propertyKey in result) { | |
if (result[propertyKey] !== propertyValue | |
&& (!(propertyKey in empty) || empty[name] !== propertyValue)) | |
{ | |
result[propertyKey] = propertyValue; | |
} | |
} else { | |
result[propertyKey] = propertyValue; | |
} | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment