(obj, seen = new WeakMap())
| 7 | * @returns {*} A deep clone of the input object |
| 8 | */ |
| 9 | export function clone (obj, seen = new WeakMap()) { |
| 10 | // Handle primitive types and null |
| 11 | if (obj === null || typeof obj !== "object") { |
| 12 | return obj; |
| 13 | } |
| 14 | |
| 15 | // Handle circular references |
| 16 | if (seen.has(obj)) { |
| 17 | return seen.get(obj); |
| 18 | } |
| 19 | |
| 20 | // Handle Date objects |
| 21 | if (obj instanceof Date) { |
| 22 | return new Date(obj.getTime()); |
| 23 | } |
| 24 | |
| 25 | // Handle RegExp objects |
| 26 | if (obj instanceof RegExp) { |
| 27 | return new RegExp(obj.source, obj.flags); |
| 28 | } |
| 29 | |
| 30 | // Handle Arrays |
| 31 | if (Array.isArray(obj)) { |
| 32 | const cloned = []; |
| 33 | seen.set(obj, cloned); |
| 34 | |
| 35 | for (let i = 0; i < obj.length; i++) { |
| 36 | const value = obj[i]; |
| 37 | // Skip functions and undefined values like JSON.stringify does |
| 38 | if (typeof value !== "function" && value !== undefined) { |
| 39 | cloned[i] = clone(value, seen); |
| 40 | } else if (value === undefined) { |
| 41 | // JSON.stringify converts undefined array elements to null |
| 42 | cloned[i] = null; |
| 43 | } else if (typeof value === "function") { |
| 44 | // Functions in arrays are converted to null by JSON.stringify |
| 45 | cloned[i] = null; |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | return cloned; |
| 50 | } |
| 51 | |
| 52 | // Handle Map objects |
| 53 | if (obj instanceof Map) { |
| 54 | const cloned = new Map(); |
| 55 | seen.set(obj, cloned); |
| 56 | |
| 57 | for (const [key, value] of obj) { |
| 58 | // Skip functions and undefined values |
| 59 | if (typeof value !== "function" && value !== undefined) { |
| 60 | cloned.set(clone(key, seen), clone(value, seen)); |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | return cloned; |
| 65 | } |
| 66 |
no outgoing calls
no test coverage detected