I am struggling with finding any good examples of coffeescript and pattern matching apart from these sort of examples:
{x, y} = sprite
css = {opacity, fontFamily}
I have used pattern matching in Erlang but I am struggling with finding some more advanced examples in coffeescript which illustrate exactly what is possible.
Ah, I thought I recognized those examples: http://pragprog.com/magazines/2011-05/a-coffeescript-intervention :)
CoffeeScript's pattern-matching (more formally called "destructuring assignment" to distinguish it from pattern-matching in Erland and Scala, which is quite different) can be used to extract information from very elaborate data structures. Here's an example from the official docs:
{poet: {name, address: [street, city]}} = futurists
which is essentially equivalent to
poet = futurists.poet
name = poet.name
street = poet.address[0]
city = poet.address[1]
In practice, though, destructuring assignment is mainly used for grabbing one or two object properties, as in the examples you mentioned, or for getting parts from an array. For instance, you can swap the values of two variables a
and b
by writing
[a, b] = [b, a]
and, using splats, you can get the first and last values of an array arr
by writing
[first, middle..., last] = arr
I hope that helps. There are of course more examples in my book, CoffeeScript: Accelerated JavaScript Development.
There is a a library which provides a way to write Erlang-like constructions right in coffeescript without precompilation, just wrap up it in special function. You can find it here: https://github.com/nogizhopaboroda/f_context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With