-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathdeep-clone.ts
31 lines (25 loc) · 863 Bytes
/
deep-clone.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// * ------------------------------------------------ deepClone simple
const deepClone = <T = any>(data: T): T => {
if (Array.isArray(data)) {
// @ts-ignore Just Works Programming LOL
return data.map((e) => deepClone(e)) as T;
} else if (typeof data === 'object') {
return Object.fromEntries(Object.entries(data).map(([k, v]) => [k, deepClone(v)])) as T;
} else {
return data;
}
};
// * ------------------------------------------------ usage
{
const data = { children: [{ id: 2 }, { id: 3 }, { id: 4 }] };
const result = deepClone(data);
console.log(result);
console.assert(result !== data);
console.assert(result.children !== data.children);
console.assert(JSON.stringify(result) === JSON.stringify(data));
}
{
const data = [{ id: 2 }, { id: 3 }, { id: 4 }];
const result = deepClone(data);
console.log(result);
}