Implement a structuredClone polyfill: cycles, Map and Set, shared typed array buffers, errors and DataCloneError

hardAbout 50 minutesUpdated CodingProjavascriptstructured-clonedeep-clonepolyfillstyped-arraysrecursion
Not solved

Share this question

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 DataCloneError

Ref. UR-1442 · © UIRound · uiround.com/questions/implement-a-structuredclone-polyfill-cycles-map-and-set-shared-typed-array-buffers-errors-and-datacloneerror

Stuck? Take a hint

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.

Every question and answer7 days, one payment