Skip to content

Instantly share code, notes, and snippets.

@dherman
Forked from syg/gist:3427627
Created August 22, 2012 17:23
Show Gist options
  • Save dherman/3427720 to your computer and use it in GitHub Desktop.
Save dherman/3427720 to your computer and use it in GitHub Desktop.

Revisions

  1. Dave Herman renamed this gist Aug 22, 2012. 1 changed file with 18 additions and 0 deletions.
    18 changes: 18 additions & 0 deletions gistfile1.txt → paproxy.js
    Original file line number Diff line number Diff line change
    @@ -19,6 +19,24 @@ function paMaker(backing) {
    delete: function(name) {
    throw new Error("immutable");
    },
    getOwnPropertyDescriptor: function(name) {
    if (isIndex(name)) {
    if (({}).hasOwnProperty.call(backing, name))
    return { enumerable: true, configurable: false, writable: false, value: backing[name] };
    // report out-of-range indices as not there
    return undefined;
    }
    return Object.getOwnPropertyDescriptor(backing, name); // or something like that
    },
    hasOwn: function(name) {
    return name in backing;
    },
    has: function(name) {
    // the "in" test for indexed properties ignores the prototype hierarchy
    if (isIndex(name))
    return name in backing;
    return name in backing || name in proto;
    },
    get: function(receiver, name) {
    if (isIndex(name)) {
    if (({}).hasOwnProperty.call(backing, name))
  2. @syg syg created this gist Aug 22, 2012.
    44 changes: 44 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    function isIndex(n) {
    // This isn't right, but pretend that this checks if n is an index in the
    // way that SpiderMonkey checks in js_IdIsIndex.
    return Number(n) % 1 == 0;
    }

    function indices(obj) {
    var result = [];
    for (var i = 0; i < obj.length; i++)
    result.push(i);
    return result;
    }

    function paMaker(backing) {
    return {
    defineProperty: function(name, desc) {
    throw new Error("immutable");
    },
    delete: function(name) {
    throw new Error("immutable");
    },
    get: function(receiver, name) {
    if (isIndex(name)) {
    if (({}).hasOwnProperty.call(backing, name))
    return backing[name];
    return undefined;
    }
    return backing[name];
    },
    set: function(receiver, name, val) {
    throw new Error("immutable");
    },
    enumerate: function() {
    return indices(obj);
    },
    keys: function() {
    return indices(obj);
    }
    };
    }

    Array.prototype[0] = "foo";
    Array.prototype[42] = "foo";
    var proxy = Proxy.create(paMaker([,2]));