title: How to write a universal "magic length" getter and setter without memory leaks?
body: <p>Here is my code:
  </p>
  
  <pre><code>function magicLengthGetter() {
      var last = Math.max.apply(null,
          Object.keys(this)
          .map(Number)
          .filter(function(el) {
              return el &gt;= 0 &amp;&amp; el === el;
          })
      );
      if (last === -Infinity) {
          return 0;
      }
      return last + 1;
  };
  
  function magicLengthSetter(val) {
      Object.keys(this).forEach(function(el, i, arr) {
          var modified = Number(el);
          if (modified === modified /* NaN check */ &amp;&amp; modified &gt;= val) {
              delete this[el];
          }
      }, this);
      return val;
  };
  function addMagicLengthProperty(what, readOnly) {
      if (arguments.length &lt; 2) {
          readOnly = true;
      }
      Object.defineProperty(what, 'length', {
          configurable: false,
          enumerable: false,
          get: magicLengthGetter,
          set: readOnly ? Function() : magicLengthSetter
      });
      return what;
  };
  </code></pre>
  
  <p>It works good most of times, but it breaks in few cases.
  Eg.
  </p>
  
  <pre><code>var wow = addMagicLength({});
  wow[3] = 'foo';
  wow.length; // 4
  wow.length = 0;
  wow[3]; // undefined
  wow.length = 50;
  wow.length; // 0; Should be 50 and be like array with holes
  </code></pre>
  
  <p>How can I fix this issue without using WeakMaps, creating copy of accessors for every instance of class or memory leaks?</p>