Deep clone and object graphs
A deep clone needs a stated data model. JSON serialization handles plain JSON values, but it can't preserve cycles, repeated references, Date objects, Maps, or Sets. A shallow spread leaves nested objects shared. Either shortcut can appear to work until a caller edits the copy.
These exercises define a graph clone for plain objects, arrays, Dates, Maps, and Sets. A WeakMap records the new object for every original object before its children are visited. That order both terminates cycles and preserves shared references inside the clone. The wrappers create identities that JSON input can't express and inspect them with equality checks. Functions, prototypes, symbols, property descriptors, and host objects are outside this lesson's supported clone contract. Don't claim a universal clone from this implementation.
function deepClone<T>(value:T, seen=new WeakMap<object,unknown>()):T {
if(value===null || typeof value!=="object")return value;
if(seen.has(value))return seen.get(value) as T;
if(value instanceof Date)return new Date(value.getTime()) as T;
if(value instanceof Map){const out=new Map<unknown,unknown>();seen.set(value,out);for(const [k,v] of value)out.set(deepClone(k,seen),deepClone(v,seen));return out as T;}
if(value instanceof Set){const out=new Set<unknown>();seen.set(value,out);for(const item of value)out.add(deepClone(item,seen));return out as T;}
const out:unknown=Array.isArray(value)?[]:{}; seen.set(value,out);
for(const key of Object.keys(value))Object.defineProperty(out,key,{value:deepClone((value as Record<string,unknown>)[key],seen),enumerable:true,writable:true,configurable:true});
return out as T;
}
function solve(value:string):string[] {const input=JSON.parse(value) as {profile:{name:string};next:string};const copy=deepClone(input);copy.profile.name=input.next;return [input.profile.name,copy.profile.name];}
A complete implementation for the first scenario; trace its input before editing.