Map, Set and their weak cousins in JavaScript
Maps take any key and remember insertion order; WeakMap holds no reference.
const byObject = new Map();
const key = { id: 1 };
byObject.set(key, "object key").set("id", "string key");
console.log(byObject.get(key), byObject.size, [...byObject.keys()].length);
const seen = new Set([1, 2, 2, 3]);
console.log(seen.size, seen.has(2), [...seen]);
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
console.log([...a].filter((x) => b.has(x)));
const cache = new WeakMap();
cache.set(key, { computed: true });
console.log(cache.has(key), cache.get(key).computed);
How it works
- An object key in a plain object becomes a string; in a Map it does not.
Setdeduplicates bySameValueZero.- A
WeakMapentry vanishes when its key is collected.
Keywords and builtins used here
MapSetWeakMapconst
The run, in numbers
- Lines
- 15
- Characters to type
- 494
- Tokens
- 194
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 123 seconds.
Step 4 of 8 in Objects & collections, step 30 of 43 in Language basics.