Skip to content

Instantly share code, notes, and snippets.

@zenparsing
Last active April 10, 2023 18:14
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zenparsing/574380599eccec7860af to your computer and use it in GitHub Desktop.
Save zenparsing/574380599eccec7860af to your computer and use it in GitHub Desktop.
Optional chaining with JS Proxy
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(target, key) { return key === unwrapSymbol ? (_=> void 0) : Nothing },
set() {},
has() { return true },
apply() { return Nothing },
construct() { return Nothing },
});
const maybeHandler = {
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)) },
};
function Maybe(x) {
return x === Nothing || x == null ? Nothing : new Proxy(Object(x), maybeHandler);
}
// alert(Maybe(self).document.scripts[0].parentNode.nodeName::unwrap());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment