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

Brendan Eich brendan at
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 here, not ===, per spec:

>                  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.


More information about the es-discuss mailing list