Skip to content
A tiny (366B) and fast utility to "deep clone" Objects, Arrays, Dates, RegExps, and more!
JavaScript
Branch: master
Clone or download

Latest commit

Fetching latest commit…
Cannot retrieve the latest commit at this time.

Files

Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.github/workflows chore: include `pull_request` trigger Jan 10, 2020
bench
src chore: fix spacing Jan 16, 2020
test fix: explicit "__proto__" guard; Jan 13, 2020
.editorconfig
.gitignore
klona.d.ts chore: rename module Jan 9, 2020
license initial commit Jan 9, 2020
logo.png chore: add readme w/ logo Jan 9, 2020
package.json
readme.md chore: update size Jan 16, 2020

readme.md

klona
A tiny (366B) and fast utility to "deep clone" Objects, Arrays, Dates, RegExps, and more!

Features

  • Super tiny and performant
  • Deep clone / recursive copies
  • Safely handles complex data types
    Array, Date, Map, Object, RegExp, Set, TypedArray

Unlike a "shallow copy" (eg, Object.assign), a "deep clone" recursively traverses a source input and copies its values — instead of references to its values — into a new instance of that input. The result is a structurally equivalent clone that operates independently of the original source and controls its own values.

Additionally, this module is delivered as:

Why "klona"? It's "clone" in Swedish.
What's with the sheep? Dolly.

Install

$ npm install --save klona

Usage

import klona from 'klona';

const input = {
  foo: 1,
  bar: {
    baz: 2,
    bat: {
      hello: 'world'
    }
  }
};

const output = klona(input);

// exact copy of original
assert.deepStrictEqual(input, output);

// applying deep updates...
output.bar.bat.hola = 'mundo';
output.bar.baz = 99;

// ...doesn't affect source!
console.log(
  JSON.stringify(input, null, 2)
);
// {
//   "foo": 1,
//   "bar": {
//     "baz": 2,
//     "bat": {
//       "hello": "world"
//     }
//   }
// }

API

klona(input)

Returns: typeof input

Returns a deep copy/clone of the input.

Benchmarks

via Node.js v10.13.0

Validation:
  ✘ JSON.stringify (FAILED @ "initial copy")
  ✘ fast-clone (FAILED @ "initial copy")
  ✔ lodash
  ✔ clone-deep
  ✘ deep-copy (FAILED @ "initial copy")
  ✔ depcopy
  ✔ klona

Benchmark:
  JSON.stringify   x  37,803 ops/sec ±0.68% (89 runs sampled)
  fast-clone       x  24,210 ops/sec ±0.81% (91 runs sampled)
  lodash           x  40,563 ops/sec ±1.10% (94 runs sampled)
  clone-deep       x  85,020 ops/sec ±0.17% (95 runs sampled)
  deep-copy        x 116,139 ops/sec ±0.29% (96 runs sampled)
  depcopy          x  24,392 ops/sec ±0.71% (96 runs sampled)
  klona            x 274,496 ops/sec ±0.15% (99 runs sampled)

Related

  • dlv – safely read from deep properties in 120 bytes
  • dset – safely write into deep properties in 160 bytes
  • dequal – safely check for deep equality in 247 bytes

License

MIT © Luke Edwards

You can’t perform that action at this time.