Deep Clone With Structured Clone Algorithm
Deep clone objects using structuredClone with fallback for older runtimes handling cycles and typed arrays.
Code
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;}What the code does
Count the functions deepClone and cloneFallback as the entire surface area of Deep Clone With Structured Clone Algorithm.
What comes back is a new object, not a reference to anything passed in.
What to watch for
- The guard
obj===null||typeof obj!=='object'short-circuits the flow with an earlyreturnwhen its condition holds.
Using it in your own code
Entry signature: export function deepClone(obj)
deepClone is what another module would consume; nothing else here is load-bearing for callers.
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does `deepClone` modify its input?
- It does not. Inputs are only read; the return value is freshly built.
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. The file defines `deepClone`, `cloneFallback` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.