Last active
November 24, 2021 15:24
-
-
Save petsel/d40b2a53e0e76f02a651912aeb5def36 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getIntersectionOfMany(...listOfIterables) { | |
function getIntersectionOfTwo(intersection, iterableItem) { | |
// ensure two arrays ... | |
const [ | |
comparisonBase, // ... the shorter one as comparison base | |
comparisonList, // ... the longer one to filter from. | |
] = [intersection, iterableItem] | |
.sort((a, b) => a.length - b.length); | |
// create a `Map` based lookup table from the shorter array. | |
const itemLookup = comparisonBase | |
.reduce((map, item) => map.set(item, true), new Map) | |
// the intersection is the result of following filter task. | |
return comparisonList.filter(item => itemLookup.has(item)); | |
} | |
const [ | |
comparisonBase, | |
...iterableRest | |
] = listOfIterables.reduce((list, item) => { | |
const iterable = (item != null) && Array.from(item); | |
if (iterable) { | |
list.push(iterable); | |
} | |
return list; | |
}, []).sort((a, b) => a.length - b.length); | |
const comparisonItem = iterableRest.pop(); | |
return (Array.isArray(comparisonItem) && Array.isArray(comparisonBase)) | |
? iterableRest | |
.concat([comparisonItem], [comparisonBase]) | |
.reduceRight((intersection, iterableItem) => | |
getIntersectionOfTwo(intersection, iterableItem) | |
) | |
: (comparisonBase ?? null); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment