Skip to content

Instantly share code, notes, and snippets.

@willmtemple
Last active January 23, 2021 22:24
Show Gist options
  • Save willmtemple/83af3347a886658a04eb5acfcb68cc08 to your computer and use it in GitHub Desktop.
Save willmtemple/83af3347a886658a04eb5acfcb68cc08 to your computer and use it in GitHub Desktop.
const values = [
{ kind: "Foo", n: 10001 },
{ kind: "Bar", s: "Hello world!" }
];
function match(value, pattern, discriminant = "kind") {
return pattern[value[discriminant]]?.(value);
}
for (const value of values) {
match(value, {
Foo: ({ n }) => {
console.log(`Encountered a Foo with n: ${n}`);
},
Bar: ({ s }) => {
console.log(`Bar came with a message: ${s}`);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment