Actual WeakSet Use Cases

Caitlin Potter caitpotter88 at gmail.com
Tue Jun 2 15:24:59 UTC 2015


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



More information about the es-discuss mailing list