Search code examples
javascriptarrayses6-proxy

Javascript: Trap "in" operator in proxy


I have a proxy something like this:

var pr = new Proxy([],...);

Without giving all the gory details, it is set up to trap integers and return objects from another (actual) array "B" at the corresponding index. So, eg, pr[3] would return B[3].someProperty. It also traps "length" and returns the length of array "B". However, values are never actually assigned directly to the pr "array". So you see it is sort of a "pseudo" array. It is merely reflecting array "B", and contains no actual values.

The problem comes in when the test (someinteger in pr) is run. Of course from what I described, this test would always return false. This test does not seem to run code in the proxy so I can't seem to trap it and compute a return for it. Or can I?

This creates a problem with Array.prototype iterator methods because many of them perform that test. I could write my own corresponding methods as traps in the proxy, but I would like to find a simpler way. If there was a way to handle the "in" operator, that would save a lot of extra code.

Is there something that I am not seeing, or a way to work around this?


Solution

  • proxy has a trap for in, it is called has:
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/has

    var a = "abcd".split("");
    var pr = new Proxy(a, {
        has: function(target, prop) {
            return (prop === "length" || +prop === (prop >>> 0) && +prop < target.length);
        },
    
        get: function(target, prop) {
            if(prop === "length") return target.length;
    
            if(+prop === (prop >>> 0) && +prop < target.length)
                return target[prop];
            return void 0;
        }
    });
    
    console.log(2 in pr, pr[2]);
    console.log(5 in pr, pr[5]);