Last active
May 15, 2019 16:46
-
-
Save seabass223/11f1dd6f53ccea1d342a1f00aff26084 to your computer and use it in GitHub Desktop.
clone recursive array
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
Array.prototype.clone = function clone<T>(this: Array<T>, deep: boolean, parent: T = null): T[] { | |
const c = this.map(x => Object.assign(Object.create(x as Object), x)); | |
const classNameMatch = (a, b) => a.constructor && b.constructor && a.constructor.name === b.constructor.name; | |
if (deep) { | |
c.forEach(i => { | |
const keys = Object.keys(i); | |
keys.forEach(k => { | |
if (i[k] instanceof Array) { | |
// an array property, let's see if it's an array of T | |
i[k] = i[k].clone(deep, i[k].length > 0 && classNameMatch(i[k][0], i) ? i : parent); | |
} else if (i[k] && classNameMatch(i[k], i)) { | |
i[k] = parent; | |
} else if (i[k] instanceof Object) { | |
i[k] = Object.assign({}, i[k]); | |
} | |
}); | |
}); | |
} | |
return c; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment