Back to Snippets
CODE
Deep Clone (Object/Array/Date/RegExp Support)
Description
Solves reference type shallow copy issues, supports deep cloning of primitive types, objects, arrays, dates, and regular expressions to avoid affecting original data when modifying copies
Code
/**
* Deep clone function
* @param target Value to be cloned
* @returns New cloned value
*/
function deepClone<T>(target: T): T {
// Return primitive types directly
if (target === null || typeof target !== 'object') return target;
// Handle Date objects
if (target instanceof Date) return new Date(target.getTime()) as T;
// Handle RegExp objects
if (target instanceof RegExp) return new RegExp(target.source, target.flags) as T;
// Handle arrays/objects
const cloneTarget = Array.isArray(target) ? [] : {} as T;
for (const key in target) {
if (Object.prototype.hasOwnProperty.call(target, key)) {
cloneTarget[key] = deepClone(target[key]);
}
}
return cloneTarget;
}
// Usage Example
const original = { a: 1, b: { c: 2 }, d: [3, 4], e: new Date() };
const copy = deepClone(original);
copy.b.c = 100;
console.log(original.b.c); // 2 (original data remains unchanged)Usage
Perfect for state management, form data duplication, and complex data processing requiring complete reference isolation