Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern Matching in coffeescript

Tags:

coffeescript

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.

like image 300
dagda1 Avatar asked Sep 16 '11 11:09

dagda1


2 Answers

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.

like image 163
Trevor Burnham Avatar answered Oct 22 '22 00:10

Trevor Burnham


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.

like image 27
Alexander Zhukov Avatar answered Oct 22 '22 00:10

Alexander Zhukov