Javascript, The Bad Parts #2: no custom comparisons in `Set` 🙀
In Javascript, Set
treats objects only by reference, not by value, requiring weird contortions to maintain unique sets of non-primitive values.
In every other modern language I've worked with, the standard library set allows custom comparisons. But not Javascript.
In Java / Kotlin, HashSet
defers to an object's hashCode
method, which can be overridden to control comparisons. With TreeSet
it's even easier: just pass a Comparator
of your own into the constructor.
Python's set
will handle any hashable value, so overriding __hash__
and __eq__
should do the trick.
Rust's HashSet
relies on the Eq
, Hash
, and PartialEq
traits---conceptually somewhat similar to Python's approach, with Rust's trait implementations and Python's special methods being two ways to accomplish much the same thing.
But in Javascript, and by extension Typescript, the standard library provides no facility for useful sets of custom types.