Created
April 26, 2017 16:06
-
-
Save coryrylan/d373c6a4172c24ab7c0b474aebeaf4d8 to your computer and use it in GitHub Desktop.
Deep copy
This file contains hidden or 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
| 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