Set polyfill with a "has" method more efficient than O(n)

Brendan Eich brendan at mozilla.org
Thu Mar 29 22:20:43 PDT 2012


Peter Michaux wrote:
> I've worked on a generic Set polyfill. It is quite a simple task to
> build one but determining if an object is in the set is O(n) with the
> following "has" method.
>
>      Set.prototype.has = function(element) {
>          for (var i = 0, ilen = this._elements.length; i<  ilen; i++) {
>              if (element === this._elements[i]) {

You need Object.is here, not ===, per

http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets

Object.is spec:

http://wiki.ecmascript.org/doku.php?id=harmony:egal

>                  return true;
>              }
>          }
>          return false;
>      };
>
> It seems like a long shot but is there some trick that someone has
> discovered that allows for a more efficient generic Set polyfill?
There's no portable way. Could you use something in the DOM, e.g. 
UserData? Not sure.

/be


More information about the es-discuss mailing list