Need private packages and team management tools?Check out npm Teams »

klona

1.1.1 • Public • Published
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

Install

npm i klona

DownloadsWeekly Downloads

470

Version

1.1.1

License

MIT

Unpacked Size

8.37 kB

Total Files

7

Last publish

Collaborators

  • avatar