From d9c51b90703a81c2ed528c1fdb1f136961b22a37 Mon Sep 17 00:00:00 2001 From: nemo-shen Date: Mon, 15 Mar 2021 20:01:14 +0800 Subject: [PATCH] =?UTF-8?q?fix(utils):=20=E8=B0=83=E6=95=B4deepClone=20(#8?= =?UTF-8?q?340)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(utils): 调整deepClone 解决deepClone没有对数组进行处理的问题 * style(utils): format * fix(utils): 删除isDef判断 T声明应该应该传入null或者undefined * fix(utils): add isDef 1. 考虑到可能会有参数同时存在oject和null两种可能性,重新增加isDef判断 2. 补全测试用例 Co-authored-by: nemo-shen <1034131477@qq.com> --- src/utils/deep-clone.ts | 15 ++++++++++++--- src/utils/test/index.spec.ts | 2 ++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/utils/deep-clone.ts b/src/utils/deep-clone.ts index 44aada0e6..bc2b88e2d 100644 --- a/src/utils/deep-clone.ts +++ b/src/utils/deep-clone.ts @@ -1,12 +1,21 @@ -import { deepAssign } from './deep-assign'; +import {isDef} from "./base"; + +export function deepClone | null | undefined>(obj: T): T { + if (!isDef(obj)) { + return obj; + } -export function deepClone>(obj: T): T { if (Array.isArray(obj)) { return (obj.map((item) => deepClone(item)) as unknown) as T; } if (typeof obj === 'object') { - return deepAssign({}, obj) as T; + const to = {} as Record; + Object.keys(obj).forEach((key) => { + to[key] = deepClone(obj[key]); + }); + + return to as T; } return obj; diff --git a/src/utils/test/index.spec.ts b/src/utils/test/index.spec.ts index c64c76034..656a2b489 100644 --- a/src/utils/test/index.spec.ts +++ b/src/utils/test/index.spec.ts @@ -11,9 +11,11 @@ import { addUnit, unitToPx } from '../format/unit'; test('deepClone', () => { const a = { foo: 0 }; const b = { foo: 0, bar: 1 }; + const c = null; const arr = [a, b]; expect(deepClone(a)).toEqual(a); expect(deepClone(b)).toEqual(b); + expect(deepClone(c)).toEqual(c); expect(deepClone(noop)).toEqual(noop); expect(deepClone(arr)).toEqual(arr); });