{"id":13447199,"url":"https://github.com/planttheidea/fast-copy","last_synced_at":"2025-05-14T06:13:31.697Z","repository":{"id":32420083,"uuid":"133025546","full_name":"planttheidea/fast-copy","owner":"planttheidea","description":"A blazing fast deep object copier","archived":false,"fork":false,"pushed_at":"2024-03-28T20:50:46.000Z","size":2222,"stargazers_count":1136,"open_issues_count":3,"forks_count":31,"subscribers_count":8,"default_branch":"master","last_synced_at":"2025-04-11T00:50:29.770Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/planttheidea.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-05-11T10:25:00.000Z","updated_at":"2025-03-13T17:52:12.000Z","dependencies_parsed_at":"2023-01-14T21:09:23.696Z","dependency_job_id":"ae07aefb-1f3c-441f-9d6a-428bfe1ddb47","html_url":"https://github.com/planttheidea/fast-copy","commit_stats":{"total_commits":140,"total_committers":12,"mean_commits":"11.666666666666666","dds":"0.30714285714285716","last_synced_commit":"ffdb4024766948886c0d27dbfe1a69ef987ae796"},"previous_names":[],"tags_count":31,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/planttheidea%2Ffast-copy","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/planttheidea%2Ffast-copy/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/planttheidea%2Ffast-copy/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/planttheidea%2Ffast-copy/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/planttheidea","download_url":"https://codeload.github.com/planttheidea/fast-copy/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254082883,"owners_count":22011773,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T05:01:10.756Z","updated_at":"2025-05-14T06:13:31.662Z","avatar_url":"https://github.com/planttheidea.png","language":"JavaScript","funding_links":[],"categories":["JavaScript","Framework agnostic packages","Javascript","🔧 Utilities \u0026 Miscellaneous"],"sub_categories":["General utilities","npm packages"],"readme":"# fast-copy\n\n\u003cimg src=\"https://img.shields.io/badge/build-passing-brightgreen.svg\"/\u003e\n\u003cimg src=\"https://img.shields.io/badge/coverage-100%25-brightgreen.svg\"/\u003e\n\u003cimg src=\"https://img.shields.io/badge/license-MIT-blue.svg\"/\u003e\n\nA [blazing fast](#benchmarks) deep object copier\n\n## Table of contents\n\n- [fast-copy](#fast-copy)\n  - [Table of contents](#table-of-contents)\n  - [Usage](#usage)\n  - [API](#api)\n    - [`copy`](#copy)\n    - [`copyStrict`](#copystrict)\n    - [`createCopier`](#createcopier)\n      - [Copier methods](#copier-methods)\n      - [Copier state](#copier-state)\n        - [`cache`](#cache)\n        - [`copier`](#copier)\n        - [`Constructor` / `prototype`](#constructor--prototype)\n    - [`createStrictCopier`](#createstrictcopier)\n  - [Types supported](#types-supported)\n  - [Aspects of default copiers](#aspects-of-default-copiers)\n    - [Error references are copied directly, instead of creating a new `*Error` object](#error-references-are-copied-directly-instead-of-creating-a-new-error-object)\n    - [The constructor of the original object is used, instead of using known globals](#the-constructor-of-the-original-object-is-used-instead-of-using-known-globals)\n    - [Generator objects are copied, but still reference the original generator's state](#generator-objects-are-copied-but-still-reference-the-original-generators-state)\n  - [Benchmarks](#benchmarks)\n      - [Simple objects](#simple-objects)\n      - [Complex objects](#complex-objects)\n      - [Big data](#big-data)\n      - [Circular objects](#circular-objects)\n      - [Special objects](#special-objects)\n  - [Development](#development)\n\n## Usage\n\n```js\nimport copy from 'fast-copy';\nimport { deepEqual } from 'fast-equals';\n\nconst object = {\n  array: [123, { deep: 'value' }],\n  map: new Map([\n    ['foo', {}],\n    [{ bar: 'baz' }, 'quz'],\n  ]),\n};\n\nconst copiedObject = copy(object);\n\nconsole.log(copiedObject === object); // false\nconsole.log(deepEqual(copiedObject, object)); // true\n```\n\n## API\n\n### `copy`\n\nDeeply copy the object passed.\n\n```js\nimport copy from 'fast-copy';\n\nconst copied = copy({ foo: 'bar' });\n```\n\n### `copyStrict`\n\nDeeply copy the object passed, but with additional strictness when replicating the original object:\n\n- Properties retain their original property descriptor\n- Non-enumerable keys are copied\n- Non-standard properties (e.g., keys on arrays / maps / sets) are copied\n\n```js\nimport { copyStrict } from 'fast-copy';\n\nconst object = { foo: 'bar' };\nobject.nonEnumerable = Object.defineProperty(object, 'bar', {\n  enumerable: false,\n  value: 'baz',\n});\n\nconst copied = copy(object);\n```\n\n**NOTE**: This method is significantly slower than [`copy`](#copy), so it is recommended to only use this when you have specific use-cases that require it.\n\n### `createCopier`\n\nCreate a custom copier based on the type-specific methods passed. This is useful if you want to squeeze out maximum performance, or perform something other than a standard deep copy.\n\n```js\nimport { createCopier } from 'fast-copy';\n\nconst copyShallow = createCopier({\n  array: (array) =\u003e [...array],\n  map: (map) =\u003e new Map(map.entries()),\n  object: (object) =\u003e ({ ...object }),\n  set: (set) =\u003e new Set(set.values()),\n});\n```\n\nEach internal copier method has the following contract:\n\n```js\ntype InternalCopier\u003cValue\u003e = (value: Value, state: State) =\u003e Value;\n\ninterface State {\n  Constructor: any;\n  cache: WeakMap;\n  copier: InternalCopier\u003cany\u003e;\n  prototype: any;\n}\n```\n\nAny method overriding the defaults must maintain this contract.\n\n#### Copier methods\n\n- `array` =\u003e `Array`\n- `arrayBuffer`=\u003e `ArrayBuffer`, `Float32Array`, `Float64Array`, `Int8Array`, `Int16Array`, `Int32Array`, `Uint8Array`, `Uint8ClampedArray`, `Uint16Array`, `Uint32Array`, `Uint64Array`\n- `blob` =\u003e `Blob`\n- `dataView` =\u003e `DataView`\n- `date` =\u003e `Date`\n- `error` =\u003e `Error`, `AggregateError`, `EvalError`, `RangeError`, `ReferenceError`, `SyntaxError`, `TypeError`, `URIError`\n- `map` =\u003e `Map`\n- `object` =\u003e `Object`, or any custom constructor\n- `regExp` =\u003e `RegExp`\n- `set` =\u003e `Set`\n\n#### Copier state\n\n##### `cache`\n\nIf you want to maintain circular reference handling, then you'll need the methods to handle cache population for future lookups:\n\n```js\nfunction shallowlyCloneArray\u003cValue extends any[]\u003e(\n  value: Value,\n  state: State\n): Value {\n  const clone = [...value];\n\n  state.cache.set(value, clone);\n\n  return clone;\n}\n```\n\n##### `copier`\n\n`copier` is provided for recursive calls with deeply-nested objects.\n\n```js\nfunction deeplyCloneArray\u003cValue extends any[]\u003e(\n  value: Value,\n  state: State\n): Value {\n  const clone = [];\n\n  state.cache.set(value, clone);\n\n  value.forEach((item) =\u003e state.copier(item, state));\n\n  return clone;\n}\n```\n\nNote above I am using `forEach` instead of a simple `map`. This is because it is highly recommended to store the clone in [`cache`](#cache) eagerly when deeply copying, so that nested circular references are handled correctly.\n\n##### `Constructor` / `prototype`\n\nBoth `Constructor` and `prototype` properties are only populated with complex objects that are not standard objects or arrays. This is mainly useful for custom subclasses of these globals, or maintaining custom prototypes of objects.\n\n```js\nfunction deeplyCloneSubclassArray\u003cValue extends CustomArray\u003e(\n  value: Value,\n  state: State\n): Value {\n  const clone = new state.Constructor();\n\n  state.cache.set(value, clone);\n\n  value.forEach((item) =\u003e clone.push(item));\n\n  return clone;\n}\n\nfunction deeplyCloneCustomObject\u003cValue extends CustomObject\u003e(\n  value: Value,\n  state: State\n): Value {\n  const clone = Object.create(state.prototype);\n\n  state.cache.set(value, clone);\n\n  Object.entries(value).forEach(([k, v]) =\u003e (clone[k] = v));\n\n  return clone;\n}\n```\n\n### `createStrictCopier`\n\nCreate a custom copier based on the type-specific methods passed, but defaulting to the same functions normally used for `copyStrict`. This is useful if you want to squeeze out better performance while maintaining strict requirements, or perform something other than a strict deep copy.\n\n```js\nconst createStrictClone = (value, clone) =\u003e\n  Object.getOwnPropertyNames(value).reduce(\n    (clone, property) =\u003e\n      Object.defineProperty(\n        clone,\n        property,\n        Object.getOwnPropertyDescriptor(value, property) || {\n          configurable: true,\n          enumerable: true,\n          value: clone[property],\n          writable: true,\n        }\n      ),\n    clone\n  );\n\nconst copyStrictShallow = createStrictCopier({\n  array: (array) =\u003e createStrictClone(array, []),\n  map: (map) =\u003e createStrictClone(map, new Map(map.entries())),\n  object: (object) =\u003e createStrictClone(object, {}),\n  set: (set) =\u003e createStrictClone(set, new Set(set.values())),\n});\n```\n\n**NOTE**: This method creates a copier that is significantly slower than [`copy`](#copy), as well as likely a copier created by [`createCopier`](#createcopier), so it is recommended to only use this when you have specific use-cases that require it.\n\n## Types supported\n\nThe following object types are deeply cloned when they are either properties on the object passed, or the object itself:\n\n- `Array`\n- `ArrayBuffer`\n- `Boolean` primitive wrappers (e.g., `new Boolean(true)`)\n- `Blob`\n- `Buffer`\n- `DataView`\n- `Date`\n- `Float32Array`\n- `Float64Array`\n- `Int8Array`\n- `Int16Array`\n- `Int32Array`\n- `Map`\n- `Number` primitive wrappers (e.g., `new Number(123)`)\n- `Object`\n- `RegExp`\n- `Set`\n- `String` primitive wrappers (e.g., `new String('foo')`)\n- `Uint8Array`\n- `Uint8ClampedArray`\n- `Uint16Array`\n- `Uint32Array`\n- `React` components\n- Custom constructors\n\nThe following object types are copied directly, as they are either primitives, cannot be cloned, or the common use-case implementation does not expect cloning:\n\n- `AsyncFunction`\n- `Boolean` primitives\n- `Error`\n- `Function`\n- `GeneratorFunction`\n- `Number` primitives\n- `Null`\n- `Promise`\n- `String` primitives\n- `Symbol`\n- `Undefined`\n- `WeakMap`\n- `WeakSet`\n\nCircular objects are supported out of the box. By default, a cache based on `WeakSet` is used, but if `WeakSet` is not available then a fallback is used. The benchmarks quoted below are based on use of `WeakSet`.\n\n## Aspects of default copiers\n\nInherently, what is considered a valid copy is subjective because of different requirements and use-cases. For this library, some decisions were explicitly made for the default copiers of specific object types, and those decisions are detailed below. If your use-cases require different handling, you can always create your own custom copier with [`createCopier`](#createcopier) or [`createStrictCopier`](#createstrictcopier).\n\n### Error references are copied directly, instead of creating a new `*Error` object\n\nWhile it would be relatively trivial to copy over the message and stack to a new object of the same `Error` subclass, it is a common practice to \"override\" the message or stack, and copies would not retain this mutation. As such, the original reference is copied.\n\n### The constructor of the original object is used, instead of using known globals\n\nStarting in ES2015, native globals can be subclassed like any custom class. When copying, we explicitly reuse the constructor of the original object. However, the expectation is that these subclasses would have the same constructur signature as their native base class. This is a common community practice, but there is the possibility of inaccuracy if the contract differs.\n\n### Generator objects are copied, but still reference the original generator's state\n\n[Generator objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator) are specific types of iterators, but appear like standard objects that just have a few methods (`next`, `throw`, `return`). These methods are bound to the internal state of the generator, which cannot be copied effectively. Normally this would be treated like other \"uncopiable\" objects and simply pass the reference through, however the \"validation\" of whether it is a generator object or a standard object is not guaranteed (duck-typing) and there is a runtime cost associated with. Therefore, the simplest path of treating it like a standard object (copying methods to a new object) was taken.\n\n## Benchmarks\n\n#### Simple objects\n\n_Small number of properties, all values are primitives_\n\n|                    | Operations / second |\n| ------------------ | ------------------- |\n| **fast-copy**      | **5,880,312**       |\n| lodash.cloneDeep   | 2,706,261           |\n| clone              | 2,207,231           |\n| deepclone          | 1,274,810           |\n| fast-clone         | 1,239,952           |\n| ramda              | 1,146,152           |\n| fast-copy (strict) | 852,382             |\n\n#### Complex objects\n\n_Large number of properties, values are a combination of primitives and complex objects_\n\n|                    | Operations / second |\n| ------------------ | ------------------- |\n| **fast-copy**      | **162,858**         |\n| ramda              | 142,104             |\n| deepclone          | 133,607             |\n| fast-clone         | 101,143             |\n| clone              | 70,872              |\n| fast-copy (strict) | 62,961              |\n| lodash.cloneDeep   | 62,060              |\n\n#### Big data\n\n_Very large number of properties with high amount of nesting, mainly objects and arrays_\n\n|                    | Operations / second |\n| ------------------ | ------------------- |\n| **fast-copy**      | **303**             |\n| fast-clone         | 245                 |\n| deepclone          | 151                 |\n| lodash.cloneDeep   | 150                 |\n| clone              | 93                  |\n| fast-copy (strict) | 90                  |\n| ramda              | 42                  |\n\n#### Circular objects\n\n_Objects that deeply reference themselves_\n\n|                    | Operations / second |\n| ------------------ | ------------------- |\n| **fast-copy**      | **2,420,466**       |\n| deepclone          | 1,386,896           |\n| ramda              | 1,024,108           |\n| lodash.cloneDeep   | 989,796             |\n| clone              | 987,721             |\n| fast-copy (strict) | 617,602             |\n| fast-clone         | 0 (not supported)   |\n\n#### Special objects\n\n_Custom constructors, React components, etc_\n\n|                    | Operations / second |\n| ------------------ | ------------------- |\n| **fast-copy**      | **152,792**         |\n| clone              | 74,347              |\n| fast-clone         | 66,576              |\n| lodash.cloneDeep   | 64,760              |\n| ramda              | 53,542              |\n| deepclone          | 28,823              |\n| fast-copy (strict) | 21,362              |\n\n## Development\n\nStandard practice, clone the repo and `yarn` (or `npm i`) to get the dependencies. The following npm scripts are available:\n\n- benchmark =\u003e run benchmark tests against other equality libraries\n- build =\u003e run `build:esm`, `build:cjs`, `build:umd`, and `build:min` scripts\n- build:cjs =\u003e build CJS files and types\n- build:esm =\u003e build ESM files and types\n- build:min =\u003e build minified files and types\n- build:umd =\u003e build UMD files and types\n- clean =\u003e run `rimraf` on the `dist` folder\n- dev =\u003e start webpack playground App\n- dist =\u003e run `clean` and `build` scripts\n- lint =\u003e run ESLint on all files in `src` folder (also runs on `dev` script)\n- lint:fix =\u003e run `lint` script, but with auto-fixer\n- prepublishOnly =\u003e run `lint`, `test:coverage`, and `dist` scripts\n- release =\u003e run `prepublishOnly` and release with new version\n- release:beta =\u003e run `prepublishOnly` and release with new beta version\n- release:dry =\u003e run `prepublishOnly` and simulate a new release\n- start =\u003e run `dev`\n- test =\u003e run AVA with NODE_ENV=test on all files in `test` folder\n- test:coverage =\u003e run same script as `test` with code coverage calculation via `nyc`\n- test:watch =\u003e run same script as `test` but keep persistent watcher\n- typecheck =\u003e run `tsc` on the codebase\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fplanttheidea%2Ffast-copy","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fplanttheidea%2Ffast-copy","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fplanttheidea%2Ffast-copy/lists"}