I am newbie of CoffeeScript so maybe my question is not constructive. If so, I am sorry. Anyway, the problem is writing function. I tried 2 ways as below but variables didn’t work well. How should I write this?
1st way: arg.foo
triangle = (arg...) ->
if arg.base == undefined then arg.base = 1;
if arg.height == undefined then arg.height = 1;
arg.base * arg.height / 2
document.writeln triangle
base:8
height:5 # => return 0.5 ...
2nd way: arg[‘foo’]
triangle = (arg...) ->
if arg['base'] == undefined then arg['base'] = 1;
if arg['height'] == undefined then arg['height'] = 1;
arg['base'] * arg['height'] / 2
document.writeln triangle
base:8
height:5 # => return 0.5 ...
Thank you for your kindness.
I’m taking this opportunity to mention a few other niceties:
Your first attempt with
arg...doesn’t work, since the...syntax (called a splat) will take the remaining arguments and put them in the arrayarg.An improvement to your default parameters is:
The construct
?=is using the existential operator, andarg.base ?= 1will assign1toarg.baseiffarg.baseisnullorundefined.But it gets even better! Coffeescript has support for destructuring assignment, so you can write:
If you prefer, you could use Coffeescript’s default arguments like this:
But that would not work if you want to be able to specify only
baseorheight, i.e. if you call it liketriangle(base: 3),heightwill beundefined, so probably not what you want.