title: Lookup table with weak references in Javascript
body: <p>I have a tree structure with elements dynamically added and removed. The elements are loaded dynamically from the network. What I want to achieve is to have a lookup table that maps the element's id to the actual element in the tree. Now, the problem when using a simple Map or Object is that it holds strong references to the tree elements which will bloat the memory after a while. Since node &gt;= 14.6.0 and Chrome &gt;= 84 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef" rel="nofollow noreferrer">supposedly support WeakRef's</a> I thought I could make a Map that holds WeakRefs to my tree elements and then simply <code>deref()</code> and see if the elements are still around. I tried to test this but it doesn't seem to work. My minimal test looks like this:</p>
  <pre class="lang-js prettyprint-override"><code>const lookup = new Map();
  let element = new Object({id:&quot;someid&quot;, data: {}});
  
  lookup.set(element.id, new WeakRef(element));
  console.dir(lookup.get(&quot;someid&quot;).deref());
  // as expected output is { id: 'someid', data: {} }
  
  element = null;
  console.log(element);
  // as expected output is null
  
  // simply calling global.gc() didn't work
  // so i made this loop which allocates mem *and* calls global.gc() to
  // force garbage collection
  // problem: infinite loop because deref always returns the dereferenced
  // value which should have gone since element was set to null
  
  while (lookup.get(&quot;someid&quot;).deref()) {
    const a = new Array(1000);
    // enabled with --expose-gc in node
    global.gc();
  }
  
  console.dir(lookup.get(&quot;someid&quot;).deref());
  </code></pre>
  <p>As written above in the comment, the issue is that the loop never ends
  because the deref call always returns a value despite the element var
  being set to null.</p>
  <p>Am I missing something here? If not and this is how it is supposed to work,
  how can I achieve my goal of having a map of weak references (WeakMap is not
  an option here, since I would have an O(n) cost of looking up an element by id)?.</p>