Jim Jim - 6 months ago 36
Javascript Question

Comparing partial objects in ramda.js

There is an equals function in Ramdajs which is totally awesome, it will provide the following:

// (1) true
R.equals({ id: 3}, { id: 3})

// (2) true
R.equals({ id: 3, name: 'freddy'}, { id: 3, name: 'freddy'})

// (3) false
R.equals({ id: 3, name: 'freddy'}, { id: 3, name: 'freddy', additional: 'item'});


How would I go about enhancing this function, or in some other way produce a
true
result for number
3


I would like to ignore all the properties of the
rValue
not present in the
lValue
, but faithfully compare the rest. I would prefer the recursive nature of
equals
remain intact - if that's possible.

I made a simple fiddle that shows the results above.

Answer

I haven't used Ramda.js before so if there's something wrong in my answer please be free to point out.

I learned the source code of Ramda.js

In src/equals.js, is where the function you use is defined.

var _curry2 = require('./internal/_curry2');
var _equals = require('./internal/_equals');

module.exports = _curry2(function equals(a, b) {
  return _equals(a, b, [], []);
});

So it simply put the function equals (internally, called _equals) into the "curry".

So let's check out the internal _equals function, it did check the length in the line 84~86:

if (keysA.length !== keys(b).length) {
  return false;
}

Just comment these lines it will be true as you wish.


You can 1) just comment these 3 lines in the distributed version of Ramda, or 2) you can add your own partialEquals function to it then re-build and create your version of Ramda (which is more recommended, from my point of view). If you need any help about that, don't hesitate to discuss with me. :)

Comments