cloneDeep
Creates a deep clone of any value. Handles plain objects, arrays, Date, RegExp, Map, Set, typed arrays, ArrayBuffer, Error, and circular references. Functions are copied by reference.
Native structuredClone is a close alternative but throws on functions, class instances, and DOM nodes. cloneDeep covers those gaps and is 2–4× faster than lodash.cloneDeep.
Import
Section titled “Import”import { cloneDeep } from "1o1-utils";import { cloneDeep } from "1o1-utils/clone-deep";Signature
Section titled “Signature”function cloneDeep<T>({ value }: CloneDeepParams<T>): TParameters
Section titled “Parameters”| Name | Type | Required | Description |
|---|---|---|---|
value | T | Yes | The value to clone |
Returns
Section titled “Returns”T — A deep clone of the input. The return type matches the input type.
Examples
Section titled “Examples”const original = { a: { b: [1, 2] }, date: new Date() };const cloned = cloneDeep({ value: original });
cloned.a.b.push(3);original.a.b; // [1, 2] — unaffected// Circular references are handledconst node: Record<string, unknown> = { name: "root" };node.self = node;
const clone = cloneDeep({ value: node });clone.self === clone; // trueclone.self === node; // false// Built-in types are preservedcloneDeep({ value: new Date("2024-06-01") }); // new Date instancecloneDeep({ value: /foo/gi }); // new RegExp instancecloneDeep({ value: new Map([["key", { x: 1 }]]) }); // new Map, values deep clonedcloneDeep({ value: new Uint8Array([1, 2, 3]) }); // new TypedArray with independent bufferEdge Cases
Section titled “Edge Cases”- Primitives (numbers, strings, booleans,
null,undefined, symbols, bigints) are returned as-is. - Functions are copied by reference — not cloned.
Mapvalues are deep cloned;Mapkeys are kept by reference (so lookups by object keys still work).Setobject values are deep cloned.- Typed arrays clone only the viewed portion of the underlying buffer (respects
byteOffset/byteLength). - Circular references are detected via a
WeakMap; the clone preserves the same cycle structure. - Uses an iterative, stack-based algorithm to avoid stack overflow on deeply nested structures.
- Custom class prototype chains are not preserved — cloned objects become plain objects. Use
structuredCloneif you need prototype preservation for serializable classes.
Also known as
Section titled “Also known as”deep clone, deep copy, clone object, copy object, structuredClone alternative
Prompt suggestion
Section titled “Prompt suggestion”I'm using 1o1-utils (npm: https://www.npmjs.com/package/1o1-utils, GitHub: https://github.com/pedrotroccoli/1o1-utils, LLM context: https://pedrotroccoli.github.io/1o1-utils/llms.txt). Show me how to use cloneDeep to snapshot nested state before mutating it