flitbit / diff

Javascript utility for calculating deep difference, capturing changes, and applying changes across objects; for nodejs and the browser.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support reference equality immutability

RoboPhred opened this issue · comments

This question was asked before at #91 but the only proposed answer was to modify the library.

I believe making this library optionally support immutable reference equality would be easy if the prefilter function also passed the lhs and rhs values to the prefilter. This would allow us to opt-in to reference equality using

function prefilterImmutable(path, key, lhs, rhs) {
  return lhs === rhs
}
diff(foo, bar, prefilterImmutable)

This allows skipping reference equality without having to modify the library's core function. The existing prefilter option is taken advantage of, and also is expanded on to allow other types of prefilters relying on the value of the thing being filtered (for example, possibly against objects signifying equality using ID properties).

It has occurred to me after writing this that a reference equality check should in fact be baked into the library, and there is no point making it optional. If two objects are the same reference, then by definition they have the same content, and there is never any need to recurse into them.

the only proposed answer was to modify the library.

You can also open a pull request

Not a perfect implementation but you have the option of passing prefilter as an object which accepts a function by key normalize which does receive lhs and rhs and you can control checks by that.

const c = DeepDiff.diff(a1, a2, {
normalize: (currentPath, key, lhs, rhs)=> lhs===rhs ? [] : [lhs,rhs],
});