theKashey / proxyequal

There is a bit more smart way to compare things, than a shallow equal.
MIT License
72 stars 7 forks source link
compare javascript proxy shallow

proxyequal

CircleCI status Greenkeeper badge

Shallow equal is a good thing, but it compares thing you don't need.

Proxy equal - "MobX"-like solution, which will "magically" compare only used keys.

NPM

Usage

The difference between proxyEqual and proxyShallow is in expectations.

Extra API

When to use proxyequal

When you have a big state, for example redux state, but some function (redux selector, or mapStateToProps) uses just a small subset.

Here proxyequal can shine, detecting the only used branches, and comparing only the used keys.

Example

import {proxyState, proxyEqual, proxyShallow} from 'proxyequal';

// wrap the original state
const trapped = proxyState(state);

// use provided one in computations
mapStateToProps(trapped.state);

// first shallow compare
proxyShallow(state, newState, trapped.affected);

// next - deep compare
proxyEqual(state, newState, trapped.affected);

Don't forget to disable

const trapped = proxyState(state);
// do something
workWith(trapped.state);

trapped.seal();

// now tracking is disabled

trapped.unseal();
// and enabled

Speed

Uses ES6 Proxy underneath to detect used branches(as MobX), and search-trie to filter out keys for shallow or equal compare.

So - it is lighting fast.

Limitations

Unfortunately, due to Proxy wrappers all objects will be unique each run.

 shallowEqual(proxyState(A), proxyState(A)) === false

There is a undocumented way to solve it, used internally in memoize-state library. Once it will be proven to work stable - we will expose it.

Compatibility

Requires Proxy support, so the proxy-polyfill is included in the common bundle for Internet Explorer 11. How this works may change in future, see issue #15 "ProxyPolyfill is unconditionally imported" for details.

Licence

MIT