Feel Physics
Feel Physics

Reputation: 2783

function definition with arguments

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.

Upvotes: 0

Views: 85

Answers (2)

Linus Thiel
Linus Thiel

Reputation: 39261

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 array arg.

An improvement to your default parameters is:

triangle = (arg) ->
    arg.base ?= 1
    arg.height ?= 1

    arg.base * arg.height / 2

The construct ?= is using the existential operator, and arg.base ?= 1 will assign 1 to arg.base iff arg.base is null or undefined.

But it gets even better! Coffeescript has support for destructuring assignment, so you can write:

triangle = ({base, height}) ->
    base ?= 1
    height ?= 1

    base * height / 2

If you prefer, you could use Coffeescript's default arguments like this:

triangle = ({base, height} = {base: 1, height: 2}) ->
    base * height / 2

But that would not work if you want to be able to specify only base or height, i.e. if you call it like triangle(base: 3), height will be undefined, so probably not what you want.

Upvotes: 1

Feel Physics
Feel Physics

Reputation: 2783

I am sorry that I found the answer. I should use arg instead of arg....

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 20 !!!

Upvotes: 0

Related Questions