Created
January 31, 2018 10:16
-
-
Save bendc/1ac7b33e386690790d17ed623493b003 to your computer and use it in GitHub Desktop.
Sets: Union, Intersection and Difference
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
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