Alex Rivera | Logout

Deconstructing a list of parameters in class constructor - Coffeescript

Asked 2012-07-15T15:29:14.573
18

If I have a class that I pass a number of parameters to:

class Foo

  constructor: (parameters) ->

  @bar = parameters.bar
  @moo = parameters.moo

The class is created like so:

foo = new Foo(bar: 2, moo: 8)

My question is what is the most elegant way to detect in the constructor if the variables being passed exist, and if not to set a default. The way I would do it in javascript would be:

this.bar = ( parameters.bar !== undefined ) ? parameters.bar : 10;

where 10 is the default.

Thanks for your help :)

Good answers - Just to summerize the best:

Inorder to detect if a parameter exists and define a default if it doesn't, in javascript is:

this.bar = ( parameters.bar !== undefined ) ? parameters.bar : 10;

and in coffescript is:

@bar = parameters.bar ? 10

So elegant and compact!

Edit
Report

1 Answer

3

You could do this using the ?= operator:

class Foo
  constructor: (parameters) ->
   @bar = parameters.bar
   @bar ?= 10
   @moo = parameters.moo
   @moo ?= 20

If you didn't mind passing in positional arguments rather than a hash, you could also do this very elegantly using default parameter values:

class Foo
  constructor: (@bar = 10, @moo = 20) ->

f = new Foo
answered 2012-07-15T16:15:16.307

Your Answer