mirror of
https://gitee.com/vant-contrib/vant.git
synced 2025-04-06 03:57:59 +08:00
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:
parent
a7fb5f732e
commit
d9c51b9070
@ -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)) {
|
||||
return (obj.map((item) => deepClone(item)) as unknown) as T;
|
||||
}
|
||||
|
||||
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;
|
||||
|
@ -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);
|
||||
});
|
||||
|
Loading…
x
Reference in New Issue
Block a user