Comparing maps
When comparing lists or sets, you only have to worry about the collection values—indexes aren't in play. When comparing maps, you have to take both the key and its value into consideration.
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 thatcountBy()
will work correctly.Map()
: Everything is wrapped...