Deep Clone With Structured Clone Algorithm

Deep clone objects using structuredClone with fallback for older runtimes handling cycles and typed arrays.

JavascriptData Integrity

Code

snippet
export function deepClone(obj){if(typeof structuredClone==='function'){try{return structuredClone(obj);}catch{}}return cloneFallback(obj,new WeakMap());}function cloneFallback(obj,seen){if(obj===null||typeof obj!=='object')return obj;if(seen.has(obj))return seen.get(obj);if(Array.isArray(obj)){const arr=[];seen.set(obj,arr);for(const i of obj)arr.push(cloneFallback(i,seen));return arr;}if(Buffer.isBuffer(obj))return Buffer.from(obj);if(obj instanceof Date)return new Date(obj);if(obj instanceof Map){const m=new Map();seen.set(obj,m);for(const[k,v]of obj)m.set(cloneFallback(k,seen),cloneFallback(v,seen));return m;}const clone={};seen.set(obj,clone);for(const[k,v]of Object.entries(obj))clone[k]=cloneFallback(v,seen);return clone;}