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 hidden or 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(); | |
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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment