fix(utils): 调整deepClone (#8340)

* 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>
This commit is contained in:
nemo-shen 2021-03-15 20:01:14 +08:00 committed by GitHub
parent a7fb5f732e
commit d9c51b9070
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 3 deletions

View File

@ -1,12 +1,21 @@
import { deepAssign } from './deep-assign'; import {isDef} from "./base";
export function deepClone<T extends Record<string, any> | null | undefined>(obj: T): T {
if (!isDef(obj)) {
return obj;
}
export function deepClone<T extends Record<string, any>>(obj: T): T {
if (Array.isArray(obj)) { if (Array.isArray(obj)) {
return (obj.map((item) => deepClone(item)) as unknown) as T; return (obj.map((item) => deepClone(item)) as unknown) as T;
} }
if (typeof obj === 'object') { if (typeof obj === 'object') {
return deepAssign({}, obj) as T; const to = {} as Record<string, any>;
Object.keys(obj).forEach((key) => {
to[key] = deepClone(obj[key]);
});
return to as T;
} }
return obj; return obj;

View File

@ -11,9 +11,11 @@ import { addUnit, unitToPx } from '../format/unit';
test('deepClone', () => { test('deepClone', () => {
const a = { foo: 0 }; const a = { foo: 0 };
const b = { foo: 0, bar: 1 }; const b = { foo: 0, bar: 1 };
const c = null;
const arr = [a, b]; const arr = [a, b];
expect(deepClone(a)).toEqual(a); expect(deepClone(a)).toEqual(a);
expect(deepClone(b)).toEqual(b); expect(deepClone(b)).toEqual(b);
expect(deepClone(c)).toEqual(c);
expect(deepClone(noop)).toEqual(noop); expect(deepClone(noop)).toEqual(noop);
expect(deepClone(arr)).toEqual(arr); expect(deepClone(arr)).toEqual(arr);
}); });