Filtering list intersections

Let's implement another intersect() function that uses method chaining to filter out the intersecting list values:

const intersection = (...lists) =>
List()
.concat(...lists)
.countBy(v => v)
.toSeq()
.filter(v => v === lists.length)
.keySeq();

This is much easier to read. Let's break down what's happening here:

  • concat(...lists): This joins all list arguments together, resulting in one big list
  • countBy(v => v): This creates a map where the keys are the unique list values, and the map values are the number or occurrences in the list
  • toSeq(): This enables lazy evaluation from this point forward
  • filter(v => v === lists.length): This finds intersecting values by checking if its count is the same as the number of lists passed to intersect()
  • keySeq(): These are the actual values that intersect, since we've filtered out those that do not

Let's put this function to use now:

const myList1 = List.of(
Map.of('first', 1, 'second', 2),
Map.of('third', 3, 'fourth', 4)
);
const myList2 = List.of(
Map.of('third', 3, 'fourth', 4),
Map.of('fifth', 5, 'sixth', 6)
);
const myList3 = List.of(
Map.of('first', 1, 'second', 2),
Map.of('third', 3, 'fourth', 4),
Map.of('seventh', 7, 'eighth', 8)
);

console.log('myList1', myList1.toJS());
// -> myList1 [ { first: 1, second: 2 }, { third: 3, fourth: 4 } ]
console.log('myList2', myList2.toJS());
// -> myList2 [ { third: 3, fourth: 4 }, { fifth: 5, sixth: 6 } ]
console.log('myList3', myList3.toJS());
// -> myList3 [ { first: 1, second: 2 },
// -> { third: 3, fourth: 4 },
// -> { seventh: 7, eighth: 8 } ]

intersection(myList1, myList2, myList3)
.forEach((v) => {
console.log('intersection', v.toJS());
});
// -> intersection { third: 3, fourth: 4 }

Now we have an intersect() function that is much easier to read because it follows the Immutable.js method chaining pattern using terse iteratee and predicate functions. It is also able to lazy filter the intersection values once the map with the counts is created.

The downside to this approach is that it does not work with duplicate values. You can make the trade off between our earlier implementation, which does allow duplicates, and this one, which does not. The reason this latter approach doesn't work with duplicate list values is because there would be no way to tell if the value exists in every list.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.88.249