Implement a structuredClone polyfill: cycles, Map and Set, shared typed array buffers, errors and DataCloneError
Problem
structuredClone(value) is how the browser copies data for postMessage, IndexedDB and history.pushState. It is not the same as JSON.parse(JSON.stringify(value)) and not the same as a typical deepClone: it keeps cycles, Map, Set, Date, binary data and errors, it drops prototypes and functions, and it throws for values it cannot send. Interviewers ask for a polyfill to see whether you know those rules, not just recursion.
const source = { when: new Date(0), tags: new Set(["a"]), bytes: new Uint8Array([1, 2]) };
source.self = source;
const copy = structuredClonePolyfill(source);
copy.self === copy; // true
copy.tags instanceof Set; // true
structuredClonePolyfill({ onClick() {} }); // throws DOMException DataCloneErrorRef. UR-1442 · © UIRound · uiround.com/questions/implement-a-structuredclone-polyfill-cycles-map-and-set-shared-typed-array-buffers-errors-and-datacloneerror
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 3
- code listings
- 7
- edge cases
- 5
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1A deep clone with a memory map (original to copy) handles cycles and shared references. Store the copy in the map before you clone its children, or a cycle recurses forever.
Try it in the editor
Run your code as often as you like. Submitting it to the full test suite is part of Pro.
Private, and saved in this browser as you type. All your notes are on My lists.