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:
which is essentially equivalent to
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
aandbby writingand, using splats, you can get the first and last values of an array
arrby writingI hope that helps. There are of course more examples in my book, CoffeeScript: Accelerated JavaScript Development.