Last active
January 23, 2021 22:24
-
-
Save willmtemple/83af3347a886658a04eb5acfcb68cc08 to your computer and use it in GitHub Desktop.
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 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