4 ms·
It does work for objects, but I imagine the problem you're describing is that JavaScript objects are equal if and only if they're the same reference, so you get
by lolinder 3y ago
It does work for objects, but I imagine the problem you're describing is that JavaScript objects are equal if and only if they're the same reference, so you get this:
const set = new Set();
set.add({});
set.add({});
// Set has 2 items [{}, {}]
const a = {};
set.add(a);
set.add(a);
// Set has only 3 items [{}, {}, {}]
The actual problem here is that JavaScript doesn't have any way to override `equals` and `hashCode` like Java does, so there's no way to change this reference-equality behavior.
- leosanchez 3y ago> The actual problem here is that JavaScript doesn't have any way to override `equals` and `hashCode` like Java does But you can use Symbols for that. no ?
- lolinder 3y agoTheoretically, if they were to add the ability to override equals they'd do it through symbols, but they haven't yet: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#static_properties https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- leosanchez 3y agoYes. Symbols are the obvious ones. Symbols and sets both came with ES6? I believe. I wonder why they haven't implemented something like that.
- vlovich123 3y agoCouldn’t you polyfill your own Set implementation using Map<Symbol, Object> where the symbol is constructed how you need it from the object?