From 8b31fa0db15ff272cc74fd0a549ff74d5dffd9f0 Mon Sep 17 00:00:00 2001 From: jfet97 Date: Thu, 10 Jan 2019 15:19:39 +0100 Subject: [PATCH] Update README.md --- README.md | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 85403a8..b60da9e 100644 --- a/README.md +++ b/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: @@ -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 @@ -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