Skip to content

Instantly share code, notes, and snippets.

@bendc
Created January 31, 2018 10:16
Show Gist options
  • Save bendc/1ac7b33e386690790d17ed623493b003 to your computer and use it in GitHub Desktop.
Save bendc/1ac7b33e386690790d17ed623493b003 to your computer and use it in GitHub Desktop.
Sets: Union, Intersection and Difference
const union = (...sets) =>
sets.reduce((acc, set) => {
set.forEach(val => acc.add(val));
return acc;
}, new Set);
const intersection = (...sets) =>
sets.reduce((acc, set) => {
set.forEach(val => {
if (sets.every(set => set.has(val)))
acc.add(val);
});
return acc;
}, new Set);
const difference = (...sets) =>
sets.reduce((acc, set) => {
const others = sets.filter(other => set != other);
set.forEach(val => {
if (others.every(set => !set.has(val)))
acc.add(val);
});
return acc;
}, new Set);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment