export class ObjectUtils { /** * @return copy of `source` object after clearing `target` object, keeping the same `target` reference */ public static copy(target: Object | any[], source: Object | any[]): Object | any[] { if (typeof target === typeof source) { ObjectUtils.clear(target); ObjectUtils.extend(target, source); return target; } else { console.error('Incompatible target and source types') } } /** * @return copy of `source` with new instance reference */ public static clone(source: Object | any[]): Object | any[] { return JSON.parse(JSON.stringify(source)); } /** * @return copy of `source` with the shared properities of `target` reference */ public static extend(target: Object | any[], source: Object | any[]): Object | any[] { if (typeof target === typeof source) { ObjectUtils.clearSharedProps(target, source); $.extend(true, target, source); return target; } else { console.error('Incompatible target and source types') } } private static clearSharedProps(target: Object | any[], source: Object | any[]) { if (typeof target == "object") { for (let prop in target) { if (target[prop] && source[prop]) { ObjectUtils.deleteRecursivly(target[prop]); delete target[prop]; } } } else if (Array.isArray(target)) { for (let i = 0; i < (target as any[]).length; i++) { ObjectUtils.clearSharedProps((target as any[])[i], source); (target as any[]).slice(i, 1); } } } /** * @delete recursivily all `target` properities */ public static clear(target: Object | any[]): void { if (Array.isArray(target)) { for (let i = 0; i < (target as any[]).length; i++) { ObjectUtils.clear((target as any[])[i]); (target as any[]).slice(i, 1); } } else if (typeof target == "object") { for (let prop in target) { this.deleteRecursivly(target[prop]); delete target[prop]; } } } private static deleteRecursivly(obj: Object | any[]): void { if (Array.isArray(obj)) { for (let i = 0; i < (obj as any[]).length; i++) { ObjectUtils.deleteRecursivly((obj as any[])[i]); (obj as any[]).slice(i, 1); } } else if (typeof obj == "object") { for (let prop in obj) { if (typeof obj[prop] == "object") { this.deleteRecursivly(obj[prop]); } else { delete obj[prop]; } } } } }