Sub topic 10
Passing Maps and Set-Like Objects
Earlier chapters always passed a real Set as the argument to union, intersection, and the other methods. That is the common case, but the methods do not require it. The argument only has to be set-like. This chapter explains what counts as set-like, how the methods use the argument internally, and why some reasonable-looking arguments, such as arrays, throw errors.
The chapter assumes you know how to create and iterate a Set, have used Map, and understand what getters and iterators are at a basic level. It also assumes the earlier chapters on union, intersection, difference, and the predicate methods.
The Set-Like Protocol
A set-like object is any object that provides three things:
| Member | Requirement | What it represents |
|---|---|---|
| `size` | A property that converts to a number other than `NaN`, and is not negative | How many elements the object holds |
| `has` | A callable method | A membership test: `has(value)` returns truthy if `value` is an element |
| `keys` | A callable method returning an iterator | A way to enumerate every element |
The argument does not have to inherit from Set or pass an instanceof check. The methods look up these three members by name and use them. This style is often called duck typing: if the object has the right shape, it is accepted.
The receiver, meaning the set before the dot, is different. It must be a genuine Set. Calling Set.prototype.union.call(someMap, otherSet) throws a TypeError, because the method needs the receiver's internal storage. Only the argument can be any set-like object.
Validation Happens Up Front
Before any element is compared, every one of these methods runs the same validation on its argument. The specification calls this step GetSetRecord. It reads size, then has, then keys, in that order, and throws as soon as something is wrong.
This has two consequences you might not expect.
First, all three members are required by every method, even methods that never use one of them. union never calls has, but an object without has still fails:
const s = new Set([1, 2]);
const onlyKeys = {
size: 1,
keys() {
return [3].values();
},
};
try {
s.union(onlyKeys);
} catch (err) {
console.log(err instanceof TypeError); // true: has is missing
}Second, size goes through numeric conversion, so size: "3" is accepted and treated as 3, and size: Infinity is also accepted. A missing size becomes undefined, which converts to NaN and throws.
Why Maps Work
A Map meets the protocol without any changes:
map.sizeis the number of entries.map.has(key)tests whether a key exists.map.keys()returns an iterator over the keys.
All three refer to keys, so a Map behaves like the set of its keys. The values are ignored.
const tags = new Set(["a", "b"]);
const counts = new Map([["b", 1], ["c", 2]]);
console.log([...tags.intersection(counts)]); // ["b"]
console.log([...tags.union(counts)]); // ["a", "b", "c"]
console.log([...tags.difference(counts)]); // ["a"]
console.log(tags.isDisjointFrom(counts)); // falseThis is useful when one collection is already a lookup table. For example, a Map from user ID to profile can be compared directly against a Set of active IDs, with no need to build a separate set of keys first.
If you want to compare against a Map's values, build a set from them: new Set(map.values()). The methods always use keys(), and nothing lets you choose a different iterator.
Why Arrays Throw
Arrays are the most common wrong argument. An array has length, not size, and it has no has method (includes is the closest equivalent). Validation fails at the first check:
const tags = new Set(["a", "b"]);
try {
tags.union(["c"]);
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // wording varies by engine
}
console.log([...tags.union(new Set(["c"]))]); // ["a", "b", "c"]The fix is to wrap the array with new Set(array). This was a deliberate design choice. Accepting arrays would have meant either an O(n) includes scan for every membership test or a hidden conversion. The committee chose to make the conversion explicit.
The table below lists common arguments and what happens with each.
| Argument | Result | Reason |
|---|---|---|
| `new Set([...])` | Works | Native set-like |
| `new Map([...])` | Works, uses keys | Has `size`, `has`, `keys` |
| `[1, 2, 3]` | `TypeError` | `size` is `undefined`, which converts to `NaN` |
| `"abc"` | `TypeError` | Not an object |
| `new WeakSet()` | `TypeError` | No `size`, no `keys` |
| `{ size: -1, has, keys }` | `RangeError` | Negative size |
| `{ size: 2, has }` | `TypeError` | `keys` missing |
| `Object.keys(obj)` | `TypeError` | It is an array, so wrap it in `new Set(...)` |
Which Members Each Method Actually Uses
After validation, the methods do not always call both has and keys. Several of them compare the two sizes and choose the cheaper strategy. They iterate the smaller collection and run membership tests against the larger one.
| Method | When `this.size <= other.size` | When `this.size > other.size` |
|---|---|---|
| `union` | Calls `other.keys()` | Calls `other.keys()` |
| `symmetricDifference` | Calls `other.keys()` | Calls `other.keys()` |
| `intersection` | Iterates `this`, calls `other.has` | Calls `other.keys()`, checks `this` |
| `difference` | Iterates `this`, calls `other.has` | Calls `other.keys()`, removes from copy |
| `isDisjointFrom` | Iterates `this`, calls `other.has` | Calls `other.keys()`, checks `this` |
| `isSubsetOf` | Iterates `this`, calls `other.has` | Returns `false` immediately |
| `isSupersetOf` | Returns `false` immediately when `this.size < other.size`; otherwise calls `other.keys()` | Calls `other.keys()` |
You can watch this happen by wrapping a set in a logging adapter:
function logged(set, label) {
return {
get size() {
console.log(`${label}: size`);
return set.size;
},
has(v) {
console.log(`${label}: has(${v})`);
return set.has(v);
},
keys() {
console.log(`${label}: keys()`);
return set.keys();
},
};
}
const small = new Set([1, 2]);
const result1 = small.intersection(logged(new Set([1, 2, 3, 4]), "big"));
// big: size
// big: has(1)
// big: has(2)
console.log([...result1]); // [1, 2]
const big = new Set([1, 2, 3, 4]);
const result2 = big.intersection(logged(new Set([2, 5]), "small"));
// small: size
// small: keys()
console.log([...result2]); // [2]In the first call, the receiver is smaller, so the method loops over it and asks the argument has. In the second call, the argument is smaller, so the method enumerates it with keys(). size is read exactly once in each call, during validation.
Writing Your Own Set-Like Object
Because size may be Infinity, a set-like object can describe a collection it could never list in full. Here is the set of all even integers:
const evens = {
size: Infinity,
has(n) {
return Number.isInteger(n) && n % 2 === 0;
},
keys() {
throw new TypeError("evens cannot be enumerated");
},
};
const nums = new Set([1, 2, 3, 4]);
console.log([...nums.intersection(evens)]); // [2, 4]
console.log([...nums.difference(evens)]); // [1, 3]
console.log(nums.isSubsetOf(evens)); // false
console.log(new Set([2, 4]).isSubsetOf(evens)); // true
console.log(nums.isDisjointFrom(evens)); // false
try {
nums.union(evens);
} catch (err) {
console.log(err.message); // "evens cannot be enumerated"
}Every finite set is smaller than Infinity, so intersection, difference, isSubsetOf, and isDisjointFrom take the has path and never call keys(). union and symmetricDifference must enumerate the argument, so they reach keys() and throw. keys still has to exist as a function, or validation would fail before anything ran. Throwing from it gives a clear message instead of an endless loop.
The same pattern fits other cases:
- A wrapper around a database-backed or remote lookup, where
hasis a cached query. - A range object such as "integers from 1 to 1,000,000", which reports its size and tests membership with arithmetic instead of storing a million values.
- A read-only view over another structure, such as the keys of a plain object.
function objectKeysView(obj) {
return {
get size() {
return Object.keys(obj).length;
},
has(key) {
return Object.hasOwn(obj, key);
},
keys() {
return Object.keys(obj).values();
},
};
}
const config = { host: "localhost", port: 8080 };
const required = new Set(["host", "port", "user"]);
console.log([...required.difference(objectKeysView(config))]); // ["user"]Gotchas With Custom Set-Likes
The methods trust the argument. They do not check that size, has, and keys agree with one another, so an inconsistent object produces wrong answers without any error.
- A wrong
sizechanges the strategy. Ifsizeis reported too small, a method may enumeratekeys()where you expectedhascalls, or the reverse. IfisSubsetOfseesthis.size > other.size, it returnsfalsewithout calling anything, even when every element is in fact present. hasandkeysmust describe the same elements. Ifkeys()yields values thathasrejects,intersectioncan give different results depending on which collection is larger.- Keys are compared with SameValueZero. Values from
keys()are added to or looked up in a realSet, so object values match only by reference, as described in the chapter on reference equality. - The result is always a plain
Set. It is never aMapand never an instance of your custom class, even when the argument was one.
Exercise
What does new Set(["x", "y"]).union({ size: 1, has: () => true, keys: () => ["z"].values() }) return, and what happens if you remove has from the argument?
Show answer
It returns a Set containing "x", "y", "z". union only enumerates keys(), so has is never called. Removing has still throws a TypeError, because validation requires has to be callable before any method runs.
Exercise
Given const m = new Map([[1, "one"], [2, "two"]]), what is [...new Set(["one", 2]).intersection(m)], and why?
Show answer
It is [2]. A Map acts as the set of its keys (1 and 2). "one" is a value, not a key, so m.has("one") is false.
Exercise
An object reports size: 0 but its has returns true for every value. What does new Set([1, 2]).isSubsetOf(obj) return, and what does that show?
Show answer
It returns false without calling has. The receiver's size (2) is greater than the argument's size (0), so the method returns early. The methods trust size, so an inaccurate size gives wrong results.
Exercise
Why does new Set([1, 2]).difference([2]) throw, and what is the simplest fix?
Show answer
An array has no size property. size reads as undefined, which converts to NaN, so validation throws a TypeError. Wrap the array: new Set([1, 2]).difference(new Set([2])) returns a Set containing 1.