Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

6
  • 4
    You could also have the constructor take a function that compares items for equality. This is good if you want this equality to be a feature of the set, rather than of the objects used in it. Commented Mar 2, 2016 at 9:37
  • 5
    @BenJ The point of generating a string and put it in a Map is that in that way your Javascript engine will use a ~O(1) search in native code for searching the hash value of your object, while accepting an equality function would force to do a linear scan of the set and check every element. Commented Sep 24, 2016 at 15:20
  • 3
    One challenge with this method is that it I think it assumes that the value of item.toIdString() is invariant and cannot change. Because if it can, then the GeneralSet can easily become invalid with "duplicate" items in it. So, a solution like that would be restricted to only certain situations likely where the objects themselves are not changed while using the set or where a set that becomes invalid is not of consequence. All of these issues probably further explain why the ES6 Set does not expose this functionality because it really only works in certain circumstances. Commented Jan 20, 2017 at 22:02
  • The problem with this answer is that (from outward appearance) item.toIdString() computes the id string independent of the contents of the instance of the GeneralSet into which it will be inserted. That precludes the possibility of a hash function - therefore validating your statement about being "memory expensive". Passing the GeneralSet as a parameter - item.toIdString(gs:GeneralSet) enables hashes to be used. Practically speaking that's the only way to do it in the "general" case (due to memory limitations) although it is obviously more work to manage the hashing. Commented Jan 13, 2021 at 2:49
  • Actually, I take back the statement that the general set "must" be checked for collisions. With a suitable toIdString() string function and and a suitable hash function hashOfIdString(), the chance of collision is sufficiently low to that it may be ignored. And the memory usage is low - making your statement about "memory expensive" be incorrect. Commented Jan 13, 2021 at 3:20