A set built on a plain object
Before Set existed, every codebase kept an object as a lookup table: selected tag ids, dismissed banner keys, feature flags already seen. It is still the shape you get back from JSON, so knowing how to do it safely matters.
Implement a UniqueSet class backed by a plain object rather than the built-in Set. It is constructed with no arguments and starts empty. add(value) stores a value and returns true if it was newly added or false if it was already present. has(value) returns true or false. delete(value) removes a value and returns true if it was present or false if it was not. size() returns how many distinct values are stored. values() returns an array of the stored values in the order they were first added, and returns [] when empty.
Every value is a word-like string such as a tag name — never a numeric string like '12'. Watch out for the classic trap: an empty object still answers to keys like toString and constructor through its prototype, so has('toString') must be false on an empty set.
Examples
const s = new UniqueSet();
s.add("react"); // true
s.add("react"); // false (already present)
s.has("react"); // true
s.values(); // ["react"]add reports whether anything new was stored.
const s = new UniqueSet();
s.has("toString"); // false — not a member
s.has("constructor"); // falseInherited object keys must not masquerade as members.
What it has to do
addreturnstruethe first time a value is stored andfalseon a repeat.hasanddeletereturnfalsefor inherited property names such astoStringandconstructor.values()lists the stored values in first-added order.values()returns an empty array andsize()returns 0 for a new set.- Do not use the built-in
SetorMap.
Notes
add,has, anddeleteare all O(1) on average — object property lookup is hashed under the hood.Object.create(null)gives you a prototype-free bag, which is whyhas('toString')can safely returnfalse.Object.keyspreserves insertion order for non-numeric string keys, which is whyvalues()can lean on it instead of maintaining a parallel list.
Stuck? The javascript course covers everything this challenge needs.
- 1.add reports whether the value was new
- 2.values lists entries in the order they were added
- 3.delete reports whether anything was removed
- 4.inherited property names are not members
- 5.a new set is empty
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.