Last active
April 10, 2023 18:14
-
-
Save zenparsing/574380599eccec7860af to your computer and use it in GitHub Desktop.
Optional chaining with JS Proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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