Skip to content

Instantly share code, notes, and snippets.

@zenparsing
Last active April 10, 2023 18:14
Show Gist options
  • 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();
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