Skip to content

Instantly share code, notes, and snippets.

@coryrylan
Created April 26, 2017 16:06
Show Gist options
  • Select an option

  • Save coryrylan/d373c6a4172c24ab7c0b474aebeaf4d8 to your computer and use it in GitHub Desktop.

Select an option

Save coryrylan/d373c6a4172c24ab7c0b474aebeaf4d8 to your computer and use it in GitHub Desktop.
Deep copy
export function deepClone<T>(obj: T): T {
let copy;
if (null === obj || 'object' !== typeof obj) {
return obj;
}
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
if (obj instanceof Array) {
copy = [];
for (let i = 0, len = obj.length; i < len; i++) {
copy[i] = deepClone(obj[i]);
}
return copy;
}
if (obj instanceof Object) {
copy = {};
for (let attr in obj) {
if (obj.hasOwnProperty(attr)) {
copy[attr] = deepClone(obj[attr]);
}
}
return copy;
}
throw new Error('Unable to copy');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment