Search code examples
javascriptfunctional-programmingramda.jstacit-programming

Is there a points-free way of filtering out tuples from a list by comparing their elements?


So I have some code which has a requirement of calling xprod with (input, input), similar to as follows:

const input = [
  { id: 1, data: 'a' },
  { id: 2, data: 'b' },
];
const product = xprod(input, input);
/* 
  [
    [ { id: 1, data: 'a' }, { id: 1, data: 'a' } ],
    [ { id: 1, data: 'a' }, { id: 2, data: 'b' } ],
    [ { id: 2, data: 'b' }, { id: 1, data: 'a' } ],
    [ { id: 2, data: 'b' }, { id: 2, data: 'b' } ],
  ] 
*/

I'd like to filter tuples in the list above by comparing the first element of the tuples to the second element in the same tuple. In this case, to remove the tuples which contain objects which have equal ids (so the 0th and 3rd elems should be filtered out -- I know in this simplified example I could use strict equality to filter, too, but that's often not the case in the code I'm actually writing).

I know I can accomplish this pretty simply with lambdas, but since I find myself ending up with this sort of data (lists of tuples) fairly often when working with ramda, I often get stuck on trying to compare one item in a tuple to another item in the same tuple in a points free manner. And maybe that's an argument to just keep it simple and use the lambda, but I'm curious if there's a different way to do it.

Here's a link to a ramda repl containing an implementation.


Solution

  • One option is to simply wrap a function that expects the two arguments of the tuple with R.apply. In your example that could be a partially applied R.eqProps.

    R.filter(R.apply(R.eqProps('id')), product)