Created
August 12, 2022 15:51
-
-
Save haeramkeem/232abb517d6672d3e783a621ec0f35ad to your computer and use it in GitHub Desktop.
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
/* Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#implementing_basic_set_operations */ | |
function isSuperset(set, subset) { | |
for (const elem of subset) { | |
if (!set.has(elem)) { | |
return false; | |
} | |
} | |
return true; | |
} | |
function union(setA, setB) { | |
const _union = new Set(setA); | |
for (const elem of setB) { | |
_union.add(elem); | |
} | |
return _union; | |
} | |
function intersection(setA, setB) { | |
const _intersection = new Set(); | |
for (const elem of setB) { | |
if (setA.has(elem)) { | |
_intersection.add(elem); | |
} | |
} | |
return _intersection; | |
} | |
function symmetricDifference(setA, setB) { | |
const _difference = new Set(setA); | |
for (const elem of setB) { | |
if (_difference.has(elem)) { | |
_difference.delete(elem); | |
} else { | |
_difference.add(elem); | |
} | |
} | |
return _difference; | |
} | |
function difference(setA, setB) { | |
const _difference = new Set(setA); | |
for (const elem of setB) { | |
_difference.delete(elem); | |
} | |
return _difference; | |
} | |
// Examples | |
const setA = new Set([1, 2, 3, 4]) | |
const setB = new Set([2, 3]) | |
const setC = new Set([3, 4, 5, 6]) | |
isSuperset(setA, setB) // returns true | |
union(setA, setC) // returns Set {1, 2, 3, 4, 5, 6} | |
intersection(setA, setC) // returns Set {3, 4} | |
symmetricDifference(setA, setC) // returns Set {1, 2, 5, 6} | |
difference(setA, setC) // returns Set {1, 2} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment