I'm writing a class
and want the instances to be comparable by <
, >
, ==
.
For <
and >
, valueOf
works fine.
==
is different, however, but I want to have that as well. I could easily implement an isEqual
method, but that's just not the same.
My current solution is a cache for all the created objects:
const cache = {}
class Comparable {
constructor (id) {
if (cache[id]) return cache[id]
cache[id] = this
}
}
That way, the comparison works. Unfortunately, this also blocks the garbage collector.
Is there another way of enabling new Comparable(42) == new Comparable(42)
, that does not impede GC?