The other answer will work fine; here is another alternative.
// Create function to check if an element is in a specified set.
function isIn(s) { return elt => s.has(elt); }
// Check if one set contains another (all members of s2 are in s1).
function contains(s1, s2) { return [...s2] . every(isIn(s1)); }
// Set equality: a contains b, and b contains a
function eqSet(a, b) { return contains(a, b) && contains(b, a); }
// Alternative, check size first
function eqSet(a, b) { return a.size === b.size && contains(a, b); }
However, be aware that this does not do deep equality comparison. So
eqSet(Set([{ a: 1 }], Set([{ a: 1 }])
will return false. If the above two sets are to be considered equal, we need to iterate through both sets doing deep quality comparisons on each element. We stipulate the existence of a deepEqual
routine. Then the logic would be
// Find a member in "s" deeply equal to some value
function findDeepEqual(s, v) { return [...s] . find(m => deepEqual(v, m)); }
// See if sets s1 and s1 are deeply equal. DESTROYS s2.
function eqSetDeep(s1, s2) {
return [...s1] . every(a1 => {
var m1 = findDeepEqual(s2, a1);
if (m1) { s2.delete(m1); return true; }
}) && !s2.size;
}
What this does: for each member of s1, look for a deeply equal member of s2. If found, delete it so it can't be used again. The two sets are deeply equal if all the elements in s1 are found in s2, and s2 is exhausted. Untested.
You may find this useful: http://www.2ality.com/2015/01/es6-set-operations.html.
===
is for value equality, not object equality. – Paigepaiknew Set([1,2,3]) != new Set([1,2,3])
. This makes Javascript Set useless for sets of sets because the superset will contain duplicate subsets. The only workaround that springs to mind is converting all subsets to arrays, sorting each array and then encoding each array as string (for example JSON). – Tan