Actual WeakSet Use Cases

Caitlin Potter caitpotter88 at gmail.com
Tue Jun 2 15:35:00 UTC 2015


Yes, we had that discussion on #whatwg already, I haven’t had my coffee yet =)


> On Jun 2, 2015, at 11:33 AM, Erik Arvidsson <erik.arvidsson at gmail.com> wrote:
> 
> Caitlin, in that example a normal Set works just as well. It can get gc'ed when you leave the iterate function.
> 
> 
> On Tue, Jun 2, 2015, 11:25 Caitlin Potter <caitpotter88 at gmail.com <mailto:caitpotter88 at gmail.com>> wrote:
> You could use it to avoid bugs involving circular references when iterating, for example:
> 
> ```js
> function iterate(O, fn) {
>   if (O == null) return O;
>   let objects = new WeakSet();
>   iterate_inner(‘’, O, objects, fn);
>   return O;
> 
>   function iterate_inner(name, O, objects, fn) {
>     for (let key of Reflect.ownKeys(O)) {
>       let value = O[key];
>       let niceName = name ? `${name}.${key}` : key;
> 
>       if (typeof value === “object” && value) {
>         // Avoid recursing into circular reference
>         if (objects.has(value)) {
>           continue;
>         } else {
>            fn(value, niceName);
>            objects.add(value);
>            iterate_inner(niceName, value, objects, fn);
>         }
>       } else {
>         fn(value, niceName);
>       }
>     }
>   }
> }
> ```
> 
> > On Jun 2, 2015, at 11:14 AM, Domenic Denicola <d at domenic.me <mailto:d at domenic.me>> wrote:
> >
> > WeakSets are perfect for branding and are how I would expect web platform class branding to be explained.
> >
> > ```js
> > const foos = new WeakSet();
> >
> > class Foo {
> >  constructor() {
> >    foos.add(this);
> >  }
> >
> >  method() {
> >    if (!foos.has(this)) {
> >      throw new TypeError("Foo.prototype.method called on an incompatible object!");
> >    }
> >  }
> > }
> > ```
> >
> > _______________________________________________
> > es-discuss mailing list
> > es-discuss at mozilla.org <mailto:es-discuss at mozilla.org>
> > https://mail.mozilla.org/listinfo/es-discuss <https://mail.mozilla.org/listinfo/es-discuss>
> 
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org <mailto:es-discuss at mozilla.org>
> https://mail.mozilla.org/listinfo/es-discuss <https://mail.mozilla.org/listinfo/es-discuss>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150602/fe484608/attachment-0001.html>


More information about the es-discuss mailing list