Skip to content

Instantly share code, notes, and snippets.

@phpnode
Created April 30, 2018 19:25
Show Gist options
  • Save phpnode/cc2b478b428d3e19fc12e475fa3406fb to your computer and use it in GitHub Desktop.
Save phpnode/cc2b478b428d3e19fc12e475fa3406fb to your computer and use it in GitHub Desktop.
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