AniUI Academy

A set built on a plain object

easyData Structures+150 XPPractice

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"); // false

Inherited object keys must not masquerade as members.

What it has to do

  • add returns true the first time a value is stored and false on a repeat.
  • has and delete return false for inherited property names such as toString and constructor.
  • values() lists the stored values in first-added order.
  • values() returns an empty array and size() returns 0 for a new set.
  • Do not use the built-in Set or Map.

Notes

  • add, has, and delete are all O(1) on average — object property lookup is hashed under the hood.
  • Object.create(null) gives you a prototype-free bag, which is why has('toString') can safely return false.
  • Object.keys preserves insertion order for non-numeric string keys, which is why values() can lean on it instead of maintaining a parallel list.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.