Skip to content

Instantly share code, notes, and snippets.

@techyaura
Last active August 23, 2019 11:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techyaura/696f0173a78dadc29f79c1624e2ec68b to your computer and use it in GitHub Desktop.
Save techyaura/696f0173a78dadc29f79c1624e2ec68b to your computer and use it in GitHub Desktop.
Javascript Sets & their implementation
/** Syntax for creating Set*/
const set = new Set();
/** Syntax for adding element to Set*/
set.add(4); // {4}
set.add(5); // {4,5}
set.add(4); // {4, 5}
/** Syntax for deleting element to Set*/
set.delete(4); // {5}
/** Syntax for checking if set contains an element */
set.has(4); // false
set.has(5); // true
/** Syntax for getting size of Set*/
set.size; // 1
/** Syntax for clear everything in Set*/
set.clear();
/** Set Utility function */
/**
* @name Interscetion
* @param setA
* @param setB
* @description Used to find intersection of two sets
*/
function intersectSets (setA, setB) {
var intersection = new Set();
for (var elem of setB) {
if (setA.has(elem)) {
intersection.add(elem);
}
}
return intersection;
}
var setA = new Set([1, 2, 3, 4]),
setB = new Set([2, 3]);
intersectSets(setA,setB); // Set {2, 3}
/**
* @name isSuperset
* @param setA
* @param subset
* @description Check if a set is superset of any subset
*/
function isSuperset(setA, subset) {
for (var elem of subset) {
if (!setA.has(elem)) {
return false;
}
}
return true;
}
var setA = new Set([1, 2, 3, 4]),
setB = new Set([2, 3]),
setC = new Set([5]);
isSuperset(setA, setB); // true
// because setA has all elements that setB does
isSuperset(setA, setC); // false
// because setA does not contain 5 which setC contains
/**
* @name unionSet
* @param setA
* @param setB
* @description return the unions of two sets
*/
function unionSet(setA, setB) {
var union = new Set(setA);
for (var elem of setB) {
union.add(elem);
}
return union;
}
var setA = new Set([1, 2, 3, 4]),
setB = new Set([2, 3]),
setC = new Set([5]);
unionSet(setA,setB); // Set {1, 2, 3, 4}
unionSet(setA,setC); // Set {1, 2, 3, 4, 5}
/**
* @name differenceSet
* @param setA
* @param setB
* @description Return the difference of two sets
*/
function differenceSet(setA, setB) {
var difference = new Set(setA);
for (var elem of setB) {
difference.delete(elem);
}
return difference;
}
var setA = new Set([1, 2, 3, 4]),
setB = new Set([2, 3]);
differenceSet(setA, setB); // Set {1, 4}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment