Hacker News new | ask | show | jobs
by aaco 3748 days ago
Google Closure Library does this in goog.structs.Set with an interesting generic solution.

A string key for the underlying map is generated based on the data type of the element being added in the set. If you're adding an object into the set, the object is mutated so that it stores a unique ID. The object's unique ID is used to form the string key that will identify this object in the set.

Note how goog.structs.Set.getKey_ is used in the add() method: https://github.com/google/closure-library/blob/v20160125/clo...

This is how the library obtains the unique ID of an object: https://github.com/google/closure-library/blob/v20160125/clo...

1 comments

I wonder if that's a problem with stuff like immutibleJS since the object itself is permanently mutated as part of being added to the set.

Also, if this was being done for ES5+ code, then either setting that property to non-enumerable or using something like Symbols would be cool since it would hopefully have a reduced impact on other code.

Depending on the implementation, yup. Since both of the most popular Immutable libraries that I know of (Immutable.js, mori) have their own API for setting properties via a `.set` method, it would not be unreasonable for them to use `Object.freeze` in order to make raw mutations throw an error.

Both libraries provide their own implementation of a Set though, so in practice you would just use the library provided one.