|
1
|
import { isObject } from "./is-object" |
|
2
|
import * as util from "node:util" |
|
3
|
|
|
4
|
/** |
|
5
|
* In most casees, JSON.parse(JSON.stringify(obj)) is enough to deep copy an object. |
|
6
|
* But in some cases, it's not enough. For example, if the object contains a function or a proxy, it will be lost after JSON.parse(JSON.stringify(obj)). |
|
7
|
* |
|
8
|
* @param obj |
|
9
|
* @param cache |
|
10
|
*/ |
|
11
|
export function deepCopy< |
|
12
|
T extends Record<any, any> | Record<any, any>[] = Record<any, any>, |
|
13
|
TOutput = T extends [] ? T[] : T |
|
14
|
>(obj: T, cache = new WeakMap()): TOutput { |
|
15
|
if (obj === null || typeof obj !== "object") { |
|
16
|
return obj as TOutput |
|
17
|
} |
|
18
|
|
|
19
|
// Handle circular references with cache |
|
20
|
if (cache.has(obj)) { |
|
21
|
return cache.get(obj) as TOutput |
|
22
|
} |
|
23
|
|
|
24
|
let copy: TOutput |
|
25
|
|
|
26
|
// Handle arrays |
|
27
|
if (Array.isArray(obj)) { |
|
28
|
copy = [] as unknown as TOutput |
|
29
|
cache.set(obj, copy) // Add to cache before recursing |
|
30
|
;(obj as Array<any>).forEach((item, index) => { |
|
31
|
;(copy as Array<any>)[index] = deepCopy(item, cache) |
|
32
|
}) |
|
33
|
return copy |
|
34
|
} |
|
35
|
|
|
36
|
if (util.types.isProxy(obj)) { |
|
37
|
return obj as unknown as TOutput |
|
38
|
} |
|
39
|
|
|
40
|
// Handle objects |
|
41
|
if (isObject(obj)) { |
|
42
|
copy = {} as TOutput |
|
43
|
cache.set(obj, copy) // Add to cache before recursing |
|
44
|
|
|
45
|
Object.keys(obj).forEach((key) => { |
|
46
|
;(copy as Record<any, any>)[key] = deepCopy( |
|
47
|
(obj as Record<any, any>)[key], |
|
48
|
cache |
|
49
|
) |
|
50
|
}) |
|
51
|
|
|
52
|
return copy |
|
53
|
} |
|
54
|
|
|
55
|
return obj as TOutput |
|
56
|
} |