Skip to content

Instantly share code, notes, and snippets.

@zenparsing
Last active April 10, 2023 18:14

Revisions

  1. zenparsing revised this gist Apr 23, 2015. 1 changed file with 17 additions and 6 deletions.
    23 changes: 17 additions & 6 deletions optional-chaining-proxy.js
    Original file line number Diff line number Diff line change
    @@ -1,8 +1,21 @@
    const unwrapSymbol = Symbol();

    function unwrap(x) {

    if (this == null)
    return this;

    let f = this[unwrapSymbol];

    if (typeof f !== "function")
    return this;

    return f.call(this);
    }

    const Nothing = new Proxy(Object.seal(function() {}), {

    get() { return Nothing },
    get(target, key) { return key === unwrapSymbol ? (_=> void 0) : Nothing },
    set() {},
    has() { return true },
    apply() { return Nothing },
    @@ -11,7 +24,8 @@ const Nothing = new Proxy(Object.seal(function() {}), {

    const maybeHandler = {

    get(target, key) { return key === unwrapSymbol ? target : Maybe(target[key]) },
    get(target, key) { return key === unwrapSymbol ? (_=> target) : Maybe(target[key]) },
    has(target, key) { return key === unwrapSymbol || key in target },
    apply(target, thisArg, argumentList) { return Maybe(target.apply(thisArg, argumentList)) },
    };

    @@ -20,8 +34,5 @@ function Maybe(x) {
    return x === Nothing || x == null ? Nothing : new Proxy(Object(x), maybeHandler);
    }

    Maybe.unwrap = function(x) {
    // alert(Maybe(self).document.scripts[0].parentNode.nodeName::unwrap());

    let val = x[unwrapSymbol];
    return val === x ? void 0 : val;
    };
  2. zenparsing created this gist Apr 23, 2015.
    27 changes: 27 additions & 0 deletions optional-chaining-proxy.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    const unwrapSymbol = Symbol();

    const Nothing = new Proxy(Object.seal(function() {}), {

    get() { return Nothing },
    set() {},
    has() { return true },
    apply() { return Nothing },
    construct() { return Nothing },
    });

    const maybeHandler = {

    get(target, key) { return key === unwrapSymbol ? target : Maybe(target[key]) },
    apply(target, thisArg, argumentList) { return Maybe(target.apply(thisArg, argumentList)) },
    };

    function Maybe(x) {

    return x === Nothing || x == null ? Nothing : new Proxy(Object(x), maybeHandler);
    }

    Maybe.unwrap = function(x) {

    let val = x[unwrapSymbol];
    return val === x ? void 0 : val;
    };