Skip to content

Instantly share code, notes, and snippets.

@andreineculau
Last active December 19, 2015 16:28
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 andreineculau/5983786 to your computer and use it in GitHub Desktop.
Save andreineculau/5983786 to your computer and use it in GitHub Desktop.
Named arguments in CoffeeScript for (a)sync funs
fun = ({subject, verb}, next) ->
# no defaults in the function definition
subject ?= 'I'
verb ?= 'dream'
result = "#{subject} #{verb}"
return next null, result if next?
result
# run
arg1 = 'We'
# async
fun {subject, verb: 'code'}, (err, result) -> console.log result
fun {}, (err, result) -> console.log result
# sync
result = fun {subject, verb: 'code'}
result = fun {} # mandatory
# required args
fun = (arg1 = 'I', arg2 = 'dream', next) ->
# same body as the named-args variant, except for the defaults
result = "#{subject} #{verb}"
return next null, result if next?
result
# optional args ?
###
you can do it, but it's either ugly, either impossible
because you cannot make more than 1-2 args optional, especially if you want to be positionally flexible
###
# run
subject = 'We'
# async
fun 'We', 'code', (err, result) -> console.log result
fun subject, 'code', (err, result) -> console.log result
# sync
result = fun subject, 'code'
result = fun subject, verb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment