1/** 2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16/** 17 * 对象拷贝工具类 18 * */ 19 20export class ObjectCopyUtil { 21 /** 22 * 判断对象是否为数组 23 * 24 * @param obj 25 * @returns 26 */ 27 private static IsArray(obj: any) { 28 return obj && typeof obj == "object" && obj instanceof Array; 29 } 30 31 /** 32 * 对象深拷贝 33 * 34 * @param tSource 35 * @returns 36 */ 37 public static DeepClone<T>(tSource: T, tTarget?: Record<string, any> | T): T { 38 if (this.IsArray(tSource)) { 39 tTarget = tTarget || []; 40 } else { 41 tTarget = tTarget || {}; 42 } 43 for (const key in tSource) { 44 if (Object.prototype.hasOwnProperty.call(tSource, key)) { 45 if (typeof tSource[key] === "object" && typeof tSource[key] !== null) { 46 tTarget[key] = this.IsArray(tSource[key]) ? [] : {}; 47 this.DeepClone(tSource[key], tTarget[key]); 48 } else { 49 tTarget[key] = tSource[key]; 50 } 51 } 52 } 53 return tTarget as T; 54 } 55 56 /** 57 * 对象浅拷贝 58 * 59 * @param tSource 60 * @returns 61 */ 62 public static SimpleClone<T>(tSource: T, tTarget?: Record<string, any> | T): T { 63 if (this.IsArray(tSource)) { 64 tTarget = tTarget || []; 65 } else { 66 tTarget = tTarget || {}; 67 } 68 for (const key in tSource) { 69 if (Object.prototype.hasOwnProperty.call(tSource, key)) { 70 tTarget[key] = tSource[key]; 71 } 72 } 73 return tTarget as T; 74 } 75}