Set
What is set?
- Set is a collection of unique values
- A value in the Set may only occur once
Write a code
const setInstance = new Set() setInstance.add(2); setInstance.add(3); setInstance.add(2); setInstance.add(3); setInstance.has(1); setInstance.has(3); console.log(setInstance); // Set(2) { 2, 3 }
Set operations
- Union: A set algorithm that compares 2 sets, and returns the third set that contains all of the unique items from the both
- Intersection: A set algorithm that compares 2 sets, and returns the third set that contains both intersecting or matching values
- Difference: A set algorithm that takes 2 input sets (set A and B), and returns all the items of A that are not available in set B
Code for a set operation
Let’s see the set operations in Javascript
function isSuperset(set, subset) { for (let item of subset) { if (!set.has(item)) { return false } } return true } function union(setA, setB) { let _union = new Set(setA) for (let item of setB) { _union.add(item) } return _union } function intersection(setA, setB) { let _intersection = new Set() for (let item of setB) { if (setA.has(item)) { _intersection.add(item) } } return _intersection } function symmetricDifference(setA, setB) { let _difference = new Set(setA) for (let item of setB) { if (_difference.has(item)) { _difference.delete(item) } else { _difference.add(item) } } return _difference } function difference(setA, setB) { let _difference = new Set(setA) for (let item of setB) { _difference.delete(item) } return _difference } 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) union(setA, setC) intersection(setA, setC) symmetricDifference(setA, setC) difference(setA, setC)