Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Array-like getter in JavaScript

I have a simple ES6 class, like so:

class Ring extends Array {
    insert (item, index) {
        this.splice(index, 0, item);
        return this;
    }
}

I want to make it so that the indexing for Ring objects wraps, so that new Ring(1, 2, 3)[3] returns 1, new Ring(1, 2, 3)[-1] returns 3, and so on. Is this possible in ES6? If so, how would I implement it?

I've read about proxies, which allow a completely customized getter, but I can't figure out how to apply a proxy to a class. I did manage this:

var myRing = new Proxy (Ring.prototype, {
    get: function (target, name) {
        var len = target.length;
        if (/^-?\d+$/.test(name))
            return target[(name % len + len) % len];
        return target[name];
    }
});

myRing is now a Ring object that supports wrapping indices. The problem is that I'd have to define Ring objects like that every time. Is there a way to apply this proxy to the class such that calling new Ring() returns it?

like image 978
ETHproductions Avatar asked Oct 01 '16 02:10

ETHproductions


2 Answers

Basically it is

class ProxyRing extends Array {
  constructor(...args) {
    super(...args)

    return new Proxy(this, {
      get: function (target, name) {
          var len = target.length;
          if (typeof name === 'string' && /^-?\d+$/.test(name))
              return target[(name % len + len) % len];
          return target[name];
      }
    });
  }

  insert (item, index) {
      this.splice(index, 0, item);
      return this;
  }
}
like image 69
Estus Flask Avatar answered Nov 16 '22 05:11

Estus Flask


Warning: This is an ugly hack

This is a rather simple approach when you think about it.

function ClassToProxy(_class, handler) {
    return (...args) => new Proxy(new _class(...args), handler);
}

This defined a function ClassToProxy. The first argument is the class you want to add behavior too, and the second is the handler.


Here's example usage:

const Ring = ClassToProxy(

    // Class
    class Ring {
        constructor(...items) {
            this.items = items;
        }
    },

    // Handler
    {
        get: function(target, name) {
            return target.items[name];
        }
    }
)
like image 3
Downgoat Avatar answered Nov 16 '22 05:11

Downgoat