Skip to content

Instantly share code, notes, and snippets.

@seabass223
Last active May 15, 2019 16:46
Show Gist options
  • Save seabass223/11f1dd6f53ccea1d342a1f00aff26084 to your computer and use it in GitHub Desktop.
Save seabass223/11f1dd6f53ccea1d342a1f00aff26084 to your computer and use it in GitHub Desktop.
clone recursive array
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