nanoclone

1.0.2 · active · verified Tue Apr 21

nanoclone is a minimalist JavaScript utility designed for deep cloning objects, weighing in at approximately 300 bytes. As of version 1.0.2, it provides a highly efficient solution for creating independent copies of various data structures, including primitives, arrays, plain objects, DOM Nodes, Date and RegExp instances, as well as Maps and Sets. A key differentiator is its ability to handle circular structures without falling into infinite loops. The library focuses on performance and a small footprint, offering a viable alternative to larger cloning libraries, especially in performance-sensitive or size-constrained environments. While its release cadence isn't explicitly defined, its small and focused scope suggests updates are primarily for bug fixes or minor enhancements. It ships with TypeScript types, enhancing developer experience in TypeScript projects.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to import and use `nanoclone` to perform a deep copy of a complex JavaScript object, including nested structures and a Date instance, verifying that the cloned object is independent of the original.

import clone from 'nanoclone';

interface DeepObject {
  num: number;
  arr: number[];
  nested: {
    obj: {
      a: number;
    };
  };
  d?: Date;
}

let a: DeepObject = {
  num: 2,
  arr: [1, 2, 3],
  nested: {
    obj: {
      a: 0
    }
  },
  d: new Date()
};

let b: DeepObject = clone(a);

// Verify independence
a.num = 10; // Change original
b.nested.obj.a = 5; // Change clone
a.d?.setFullYear(2000); // Change original Date

console.log('Original object:', a); 
// Expected: { num: 10, arr: [1, 2, 3], nested: { obj: { a: 0 } }, d: Date(2000...) }
console.log('Cloned object:', b);  
// Expected: { num: 2, arr: [1, 2, 3], nested: { obj: { a: 5 } }, d: Date(current year...) }

view raw JSON →