coffeescript tricks
a selection of artisanal amuse bouche
Like all programming languages, coffeescript has a number of subtle treasures. In this post I'll catalog several of my favorites. Enjoy!
Destructuring assignment
Destructuring assignment is a really cool feature which lets you initialize one or more variables by pattern matching them to an existing object or array. I use this everywhere in my code.
Although the docs clearly illustrate the syntax, I get the impression that most people ignore it when first learning the language. Here's a simple example:
{readFileSync} = require 'fs'
data = readFileSync 'myfile', 'utf8'
For a more complex example, let's assume we have an array of email objects which look like: {address: String, isVerified: Boolean}
. This code will loop through the verified emails and look for "fake" addresses:
for {address, isVerified} in emails when isVerified
[username, domain] = address.split '@'
if domain is 'example.com' then console.log "#{username} is fake!"
Notice how we used destructuring assignment to break apart both the email object, and the address.
Key interpolation
You can't use variables as keys in object literals. For example:
key = 'score'
value = 100
game = key: value
game
now equals {key: 100}
which clearly isn't what we intended. The standard workaround is to use bracket notation:
key = 'score'
value = 100
game = {}
game[key] = value
This time game
is {score: 100}
. In coffeescript >= 1.9.1
we can skip the brackets and use interpolation:
key = 'score'
value = 100
game = "#{key}": value
This technique can greatly simplify your code when generating complex objects. Note that if you use meteor, this should be available in version 1.2
.
Splats apply
Splats are commonly used when writing functions with a variable number of arguments:
firstTwo = (first, second, rest...) ->
console.log "#{first} is first and #{second} is second!"
and when destructuring arrays in clever ways:
[first, middle..., last] = cats
However, they can also be used as a shorthand for apply
. Let's say we need to find the maximum number in an array called scores
. The standard way to do that is:
Math.max.apply null, scores
Using splats, we can accomplish the same thing with this compact syntax:
Math.max scores...