A tiny (228B) and fast utility to "deep clone" Objects, Arrays, Dates, RegExps, and more!
Features
- Super tiny and performant
- Deep clone / recursive copies
- Safety with
Date
s and RegExp
s
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);
assert.deepStrictEqual(input, output);
output.bar.bat.hola = 'mundo';
output.bar.baz = 99;
console.log(
JSON.stringify(input, null, 2)
);
API
klona(input)
Returns: typeof input
Returns a deep copy/clone of the input.
Benchmarks
via Node.js v10.15.3
Validation:
✘ fast-clone (FAILED @ "intial copy")
✔ lodash
✔ clone-deep
✘ deep-copy (FAILED @ "intial copy")
✔ depcopy
✔ klona
Benchmark:
fast-clone x 22,323 ops/sec ±1.41% (90 runs sampled)
lodash x 39,066 ops/sec ±1.50% (90 runs sampled)
clone-deep x 81,136 ops/sec ±1.32% (91 runs sampled)
deep-copy x 109,054 ops/sec ±1.27% (94 runs sampled)
depcopy x 23,686 ops/sec ±0.75% (96 runs sampled)
klona x 238,643 ops/sec ±1.90% (92 runs sampled)
Related
- dlv – safely read from deep properties in 120 bytes
- dset – safely write into deep properties in 160 bytes
License
MIT © Luke Edwards