Skip to content

Instantly share code, notes, and snippets.

@petsel
Last active November 24, 2021 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petsel/d40b2a53e0e76f02a651912aeb5def36 to your computer and use it in GitHub Desktop.
Save petsel/d40b2a53e0e76f02a651912aeb5def36 to your computer and use it in GitHub Desktop.
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