Created
February 26, 2017 19:09
-
-
Save clohr/44d4aa6fb749b3abd4e7fcde82e03d29 to your computer and use it in GitHub Desktop.
ES6 Sets: Intersection, Difference, and Union
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 a = new Set([1, 2, 3, 4, 4, 4]) | |
const b = new Set([3, 4, 5, 6]) | |
const intersect = (set1, set2) => [...set1].filter(num => set2.has(num)) | |
const differ = (set1, set2) => [...set1].filter(num => !set2.has(num)) | |
const joinSet = (set1, set2) => [...set1, ...set2] | |
const myIntersectedSet = new Set(intersect(a, b)) | |
console.log('myIntersectedSet', myIntersectedSet) | |
const myDifferenceSet = new Set(differ(a, b)) | |
console.log('myDifferenceSet', myDifferenceSet) | |
const myJoinedSet = new Set(joinSet(a, b)) | |
console.log('myJoinedSet', myJoinedSet) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Creating a set from an existing array will remove duplicates automatically. Then, you can use the spread operator to destructure the original sets to create unions, intersections, and differences.