Synopsis: We seek to understand the Set object in JavaScript.
The Set object in JavaScript is a data structure that allows you to store only unique primitives (or ECMAScript Language types) or object references. Uniqueness is determined using the SameValueZero comparison algorithm. The SameValueZero comparison algorithm checks if the values are functionally identical in all contexts (not a strict, as in ===, equality). 1
, "1"
, and -1
can all be added to a Set.
Set objects can be iterated and even possess a Set.prototype.forEach
functionally similar to Array's and Map's. Set objects do not have mutable order and operate in order of insertion to the Set.
The Set object was originally defined in ECMA-262's 6th Edition, "ECMAScript 2015 Language Specification". As of this writing, Sets are not implemented in IE11 and Android 4.4/5.0, but otherwise are generally compatible with modern browsers.[1]
It is also worth noting that within the ECMAScript Specification, the Set data structure is intended to describe the observable semantics of Set objects, and are not necessarily intended to be a viable implementation model.[1:1]
Examples
let newSet = new Set();
newSet instanceof Set; // true
newSet.add(1); // Adds 1 to Set.
newSet.add(2).add(3); // Chaining works! Adds 2 and 3 to Set.
newSet.forEach(function(f) {
console.log(f);
})
// 1
// 2
// 3
newSet.size; // 3
newSet.delete(1); // true
newSet.delete(20); // false
newSet.has(1) // false
newSet.has(2) // true
Examples of functional set operations
/**
* setIntersection
* @function
* @param {Set} set0
* @param {Set} set1
* @returns {Set} Containing the elements that exist
* in both sets.
*/
function setIntersection(a, b) {
let setA = new Set(a),
setB = new Set(b),
intersection = new Set(),
values = setA.values();
for (let value of values) {
if (setB.has(value)) {
intersection.add(value)
}
}
return intersection;
}
/**
* setUnion
* @function
* @param {Set} set0
* @param {Set} set1
* @returns {Set} Containing elements of both given sets.
*/
function setUnion(set0, set1) {
let joined = set0.concat(set1),
result = new Set(joined);
return result;
}
/**
* setDifference
* @function
* @param {Set} set0
* @param {Set} set1
* @returns {Set} Containing all the elements in the first
* set not present in the second.
*/
function setDifference(set0, set1) {
set1.forEach(function(f) {
set0.delete(f);
})
return set0;
}
/**
* isSetSubset
* @function
* @param {Set} set
* @param {Set} subset
* @returns {Boolean} If {subset} is a subset of {primary}
* set: returns true; otherwise false.
*/
function isSetSubset(set, subset) {
let flag = null;
subset.forEach(function(f) {
if(set.has(f)) {
flag = true;
} else {
flag = false;
}
})
return flag;
}
ECMAScript 2017 Language Specification, available at https://tc39.github.io/ecma262/#sec-set-objects ↩︎ ↩︎