Skip to content

Instantly share code, notes, and snippets.

@ericelliott
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericelliott/ab30756fb61f34d2f82e to your computer and use it in GitHub Desktop.
Save ericelliott/ab30756fb61f34d2f82e to your computer and use it in GitHub Desktop.
Idiomatic CoffeeScript

Idiomatic CoffeeScript

I'm new to CoffeeScript, so I'm just using this to document idioms that I am using. Suggestions / improvements are very welcome.

IIFE (Immediately Invoked Function Expressions)

increment = do ->
  x = 0

  (amount) ->
  x += amount

No-op

noop = (->)

or as a lambda...

foo(->)

Named parameters

CoffeeScript supports destructuring assignment, which makes named params a breeze:

foo = ({param1, param2}) ->
  console.log(param1, param2)


# ... elsewhere
foo({
  param1: 'value'
  param2: 'another value'
})

Args...

CoffeeScript supports rest params, which means that you can use ... to create an array of the remaining parameters. Useful.

foo = (fn, context, args...) ->
  args.unshift('foo')
  fn.apply(context, args)

Common loop over object properties

This patches a common problem.

for own key, stream of streams
  stream.end = (->)

Which replaces the following JavaScript:

var key, stream = highland();

for (key in streams) {
  if ( streams.hasOwnProperty(key) ) {
    stream = streams[key];
    stream.end = (function() {});
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment