Sub topic 10
Passing Maps and Set-Like Objects
This chapter assumes you know how to create and iterate a Set, have used Map, and understand how iterators work, including next() and Symbol.iterator. It also builds on the union, intersection, and difference methods from earlier chapters.
The receiver of a Set method, the object before the dot, must be a real Set. The argument does not need to be one. It only has to be set-like. A set-like object is any object that provides three members:
| Member | Requirement | Used for |
|---|---|---|
| `size` | Converts to a number that is not `NaN` and not negative | Deciding which side to loop over |
| `has(value)` | A function that returns truthy or falsy | Checking membership |
| `keys()` | A function that returns an iterator with a `next()` method | Listing every element |
Maps Work Out of the Box
A Map has size, has, and keys, so it is set-like. Its keys count as the elements and its values are ignored. The result is always a new Set, never a Map.
const inStock = new Set(["apple", "pear", "plum"]);
const prices = new Map([
["pear", 1.2],
["plum", 0.9],
["kiwi", 0.5],
]);
console.log([...inStock.intersection(prices)]); // ["pear", "plum"]
console.log([...inStock.difference(prices)]); // ["apple"]
console.log(inStock.union(prices) instanceof Set); // trueWhy Arrays Throw
An array has no size property. Reading size gives undefined, which converts to NaN, so the method throws a TypeError before doing any work. Wrap the array first:
const tags = new Set(["a", "b"]);
const incoming = ["b", "c"];
try {
tags.union(incoming);
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log([...tags.union(new Set(incoming))]); // ["a", "b", "c"]Every Set method checks its argument the same way, up front, before it reads any elements:
Both has and keys must be functions, even when the operation will end up calling only one of them.
Writing Your Own Set-Like Object
You can describe a set without storing it. In the example below, evens stands for every even integer. Its size is Infinity, which passes the size check.
const evens = {
size: Infinity,
has(x) {
return Number.isInteger(x) && x % 2 === 0;
},
keys() {
throw new Error("cannot list every even number");
},
};
const nums = new Set([1, 2, 3, 4, 5, 6]);
console.log([...nums.intersection(evens)]); // [2, 4, 6]
console.log([...nums.difference(evens)]); // [1, 3, 5]
console.log(nums.isDisjointFrom(evens)); // false
try {
nums.union(evens);
} catch (err) {
console.log(err.message); // "cannot list every even number"
}This works because each method picks its strategy from the sizes:
unionandisSupersetOfalways callkeys(), because they need every element of the argument.intersection,difference, andisDisjointFromloop over whichever side is smaller. Ifthis.size <= other.size, they iterate the receiver and callother.has(). Otherwise they iterateother.keys()and callthis.has().isSubsetOfcallsother.has()for each element of the receiver. It returnsfalsestraight away if the receiver is larger.
For a finite custom object, keys() can return an array iterator, because array iterators already have next():
const allowed = {
items: ["read", "write"],
get size() {
return this.items.length;
},
has(x) {
return this.items.includes(x);
},
keys() {
return this.items.values();
},
};
const requested = new Set(["read", "write", "delete"]);
console.log([...requested.difference(allowed)]); // ["delete"]
console.log(requested.isSupersetOf(allowed)); // trueThe keys() method must return the iterator itself. A method that returns an array, or an object with only Symbol.iterator, fails, because the Set method calls next() on the returned object directly.
Common Errors
| Argument | What happens |
|---|---|
| Array | `TypeError`, because `size` is `undefined` |
| `{ size: 2, has }` with no `keys` | `TypeError`, even for `intersection` |
| `{ size: -1, has, keys }` | `RangeError` |
| `keys()` returns an array | `TypeError` when iteration starts |
| Plain object used as a dictionary | `TypeError`; build a `Set` from `Object.keys(obj)` instead |
Exercise
Given const s = new Set([1, 2]); and const m = new Map([[2, "x"], [3, "y"]]);, what does [...s.union(m)] return, and what happens if you call s.union([2, 3]) instead?
Show answer
[1, 2, 3]. The Map's keys 2 and 3 count as its elements, the duplicate 2 appears once, and the values "x" and "y" are ignored. Calling s.union([2, 3]) throws a TypeError, because an array has no size property. Use s.union(new Set([2, 3])) instead.
Exercise
An object { size: Infinity, has: (x) => x > 0, keys() { throw new Error("no"); } } is passed to new Set([-1, 5]).intersection(...). Does it throw, and if not, what is the result?
Show answer
It does not throw. The receiver's size (2) is less than or equal to Infinity, so intersection iterates the receiver and calls has on each element. keys is never called. The result is a Set containing only 5.