Actual WeakSet Use Cases

Erik Arvidsson erik.arvidsson at gmail.com
Tue Jun 2 15:33:37 UTC 2015


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> 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> 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
> > https://mail.mozilla.org/listinfo/es-discuss
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150602/079fff5d/attachment.html>


More information about the es-discuss mailing list