Skip to content

Instantly share code, notes, and snippets.

@rentzsch
Created May 5, 2010 02:55
Show Gist options
  • Save rentzsch/390325 to your computer and use it in GitHub Desktop.
Save rentzsch/390325 to your computer and use it in GitHub Desktop.
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