fast-copy
A blazing fast deep object copier
Table of contents
Usage
import copy from "fast-copy";
import { deepEqual } from "fast-equals";
const object = {
array: [123, { deep: "value" }],
map: new Map([["foo", {}], [{ bar: "baz" }, "quz"]])
};
const copiedObject = copy(object);
console.log(copiedObject === object); // false
console.log(deepEqual(copiedObject, object)); // true
Options
isStrict
Starting in 2.0.0
, you can use the isStrict
option to copy the object based on strict standards, meaning:
- Properties retain their original property descriptor
- Non-enumerable properties are copied
- Non-standard properties (e.g., keys on an
Array
object) are copied
This is significantly slower, so you should only use this if you believe it necessary.
console.log(copy(object, { isStrict: true }));
NOTE: This option is also aliased as copy.strict
.
console.log(copy.strict(object));
realm
Under the hood, fast-copy
uses instanceof
to determine object types, which can cause false negatives when used in combination with iframe
-based objects. To handle this edge case, you can pass the realm
in options, which identifies which realm the object comes from and will use that realm to drive both comparisons and constructors for the copies.
<iframe srcdoc="<script>var arr = ['foo', 'bar'];</script>"></iframe>
const iframe = document.querySelector("iframe");
const arr = iframe.contentWindow.arr;
console.log(copy(arr, { realm: iframe.contentWindow })); // ['foo', 'bar']
Types supported
The following object types are deeply cloned when they are either properties on the object passed, or the object itself:
Array
ArrayBuffer
Buffer
DataView
Date
Float32Array
Float64Array
Int8Array
Int16Array
Int32Array
Map
Object
RegExp
Set
Uint8Array
Uint8ClampedArray
Uint16Array
Uint32Array
React
components- Custom constructors
The following object types are copied directly, as they are either primitives, cannot be cloned, or the common use-case implementation does not expect cloning:
AsyncFunction
Boolean
Error
Function
GeneratorFunction
Number
Null
Promise
String
Symbol
Undefined
WeakMap
WeakSet
Circular objects are supported out of the box as well. By default a cache based on WeakSet
is used, but if WeakSet
is not available then a standard Object
fallback is used. The benchmarks quoted below are based on use of WeakSet
.
Benchmarks
Simple objects
Small number of properties, all values are primitives