Skip to content

Instantly share code, notes, and snippets.

@AGhost-7
Last active August 29, 2015 14:22
Show Gist options
  • Save AGhost-7/cbc1c523ac399c11072a to your computer and use it in GitHub Desktop.
Save AGhost-7/cbc1c523ac399c11072a to your computer and use it in GitHub Desktop.
Very basic Coffeescript pattern matching
class Message
class Greeting extends Message
class Shout extends Message
class Farewell extends Message
# Curry for reusing the match
match = (patterns...) -> (val) ->
for pat in patterns
if val instanceof pat[0] then return pat[1](val)
matcher = match(
[Greeting, -> console.log('hello!')]
[Shout, -> console.log('*SHOUTS*')]
[Message, (val) ->
for i in [1..5]
console.log('match not found for value ', val)
]
)
matcher(new Greeting)
matcher(new Shout)
matcher(new Farewell)
# >hello!
# >*SHOUTS*
# >match not found for value {}
# >match not found for value {}
# >match not found for value {}
# >match not found for value {}
# >match not found for value {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment