-
-
Notifications
You must be signed in to change notification settings - Fork 7.6k
Expand file tree
/
Copy pathdeepclone.js
More file actions
28 lines (21 loc) · 752 Bytes
/
deepclone.js
File metadata and controls
28 lines (21 loc) · 752 Bytes
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
function deepClone(value, hash = new WeakMap()) {
// Handle primitives
if (value === null || typeof value !== "object") return value;
// Handle circular references
if (hash.has(value)) return hash.get(value);
// Handle Date
if (value instanceof Date) return new Date(value);
// Handle RegExp
if (value instanceof RegExp) return new RegExp(value);
// Handle Arrays or Objects
const clone = Array.isArray(value) ? [] : {};
// Store reference in WeakMap (for circular structures)
hash.set(value, clone);
// Recursively clone properties
for (let key in value) {
if (value.hasOwnProperty(key)) {
clone[key] = deepClone(value[key], hash);
}
}
return clone;
}