Map intersections

Let's modify our intersection() function so that it works with maps. When we're looking for the intersection of two or more maps, the result should be another map with the intersecting key-value pairs. Here's the new version of intersection():

const intersection = (...maps) =>
Map(List()
.concat(...maps.map(m => m.entrySeq()))
.map(List)
.countBy(v => v)
.toSeq()
.filter(v => v === maps.length)
.keySeq());

There are three differences between this implementation and the earlier implementation that works with lists:

  • ...maps.map(m => m.entrySeq()): This turns every map into an array of key-value pair arrays.
  • .map(List): This turns every key-value array into a key-value list so that countBy() will work correctly.
  • Map(): Everything is wrapped in Map(), since this is what we want to return. The Map() constructor gets key-value pairs passed to it.

Now let's see this function in action:

const myMap1 = Map.of(
'one', 1, 'two', 2, 'three', 3
);
const myMap2 = Map.of(
'one', 1, 'three', 3, 'four', 4
);
const myMap3 = Map.of(
'one', 1, 'two', 2, 'five', 5
);

console.log('intersection');
intersection(myMap1, myMap2, myMap3)
.forEach((v, k) => console.log(k, v));
// -> intersection
// -> one 1
..................Content has been hidden....................

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