Skip to content

traverse clone()

Eugene Lazutkin edited this page May 8, 2026 · 7 revisions

Creates a deep clone of a JavaScript object with support for circular references, custom types, and variables.

Introduction

This is the underlying implementation used by the main clone() function. It provides more control over the cloning process through options and custom processors.

import clone from 'deep6/traverse/clone.js';

const original = {a: 1, b: {c: 2}, d: new Date()};
const cloned = clone(original);

// cloned is a deep copy with new Date instance

API

clone(source [, env] [, options])

Arguments:

  • source — a required value to clone. It can be anything.
  • env — an optional Env for resolving variables during cloning, or an options object.
  • options — an optional object. The following optional properties are recognized:
    • circular — a boolean flag. When true, handles circular references correctly.
    • symbols — a boolean flag. When true, clones symbol properties.
    • allProps — a boolean flag. When true, clones non-enumerable properties.
    • context — a custom context object for processors.
    • processObject — a custom object processor function.
    • processOther — a custom value processor function.
    • processCircular — a custom circular reference processor.
    • registry — a custom type handler registry (flat array of Constructor/handler pairs). See walk().
    • filters — custom filter functions (value, context) => boolean. Return true to indicate the value was handled. See walk().

The function returns a deep clone of source.

Registry

The clone module exports registry and filters arrays for extending clone behavior. Each registry handler receives (val, context) and must push the cloned value to context.stackOut:

import clone from 'deep6/traverse/clone.js';

// Add custom type cloning
clone.registry.push(MyClass, (val, context) => {
  context.stackOut.push(new MyClass(val.data));
});

Built-in registry handles: Command, Array, Variable, Unifier, Date, RegExp, Map, Promise, URL, Set, typed arrays, DataView, and ArrayBuffer.

Notes

Implemented using walk().

Clone this wiki locally