Skip to content

Instantly share code, notes, and snippets.

@bendc
Created January 31, 2018 10:16
Embed
What would you like to do?
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