Skip to content

Commit

Permalink
Update README.md
Browse files Browse the repository at this point in the history
  • Loading branch information
jfet97 committed Jan 10, 2019
1 parent 93da740 commit 8b31fa0
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion README.md
@@ -1,7 +1,7 @@
# omniclone [![NPM version](https://img.shields.io/npm/v/omniclone.svg)](https://www.npmjs.com/package/omniclone) [![license](https://img.shields.io/github/license/mashape/apistatus.svg)](https://github.com/jfet97/omniclone/blob/master/LICENSE) ![](https://img.shields.io/npm/dt/omniclone.svg)
An isomorphic and configurable javascript function for object deep cloning.
```js
omniclone(source [, config]);
omniclone(source [, config, [, visitor]]);
```

Example:
Expand Down Expand Up @@ -36,6 +36,7 @@ import omniclone from 'omniclone';
6. similar references are not duplicated
7. correct cloning of Array objects
8. correct cloning of RegExp and Date objects
9. let you define custom cloning logic

## config

Expand Down Expand Up @@ -220,6 +221,31 @@ JSON.stringify(source); // '{"a":{"foo":"bar"},"b":{"foo":"bar"}}'
```
When you will use `JSON.parse()`, an `{"foo":"bar"}` object will be created for the `a` prop and a `{"foo":"bar"}` distinct object will be created for the `b` prop. But this is not the initial situation where `source.a == source.b; // true`.

## how to define custom cloning logic?
You can define a callback function that will be called on each node which copy can be customized:
```js
function visitor(node, config) {
// do stuff
}
```
The function will receive the `node` and a copy of the `config` object. If the function returns something different than `undefined`, that returned value will become the cloned value. On the contrary if the function returns `undefined` the default cloning algorithm will be used.

You cannot overwrite the default algorithm logic for String, Boolean, Number, Error, Promise, Map, Set, WeakMap, WeakSet, Date and RegExp objects.
You can overwrite the default algorithm logic for Array, ArrayBuffer, TypedArray, DataView, plain js and custom objects.

Let's see an example where we add custom logic to properly clone a Node.js Buffer object:
```js
const buffer = Buffer.from([1, 2, 3, 4]);

const resBuffer = omniclone(buffer, {}, node => {
if (node instanceof Buffer) { // it affects only Buffer objects
return Buffer.from(node);
}
return undefined; // all the other node will be cloned as usual
});
```
Thanks to the `instanceof` check, only Buffer objects will be affected by the intervention of the visitor callback.


## warnings and limitations
1. promises and methods are always copied by reference
Expand Down

0 comments on commit 8b31fa0

Please sign in to comment.