http://ivanzuzak.info/2009/08/09/named-arguments-in-javascript.html
Last active
December 19, 2015 16:28
-
-
Save andreineculau/5983786 to your computer and use it in GitHub Desktop.
Named arguments in CoffeeScript for (a)sync funs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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