Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
const invalidMatchSignal = new Error();
function makeProxyThrower(input) {
return new Proxy(input, {
get(target, prop, receiver) {
if (prop in target) {
const result = Reflect.get(target, prop, receiver);
if (typeof result === "object" && result !== null) {
return makeProxyThrower(result);
}
return result;
}
throw invalidMatchSignal;
}
});
}
function match(input, ...patterns) {
const param = makeProxyThrower(input);
for (const pattern of patterns) {
try {
return pattern(param);
} catch (e) {
if (e !== invalidMatchSignal) {
throw e;
}
}
}
throw new Error("No match for input");
}
console.log(match({ foo: "bar" }, ({ bar }) => "nope", ({ foo }) => "ok"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment