1

In Coffeescript, what's the best way to create a function with mandatory parameters? At the moment, I'm doing this:

myFunction: (requiredParam, optionalParam) ->
    unless requiredParam? then throw new Error ...
    ...

If I have, say, 5 parameters or even more, it takes quite a lot of time and space to throw an error for each parameter.

Is there a simpler/more concise way of doing this?

Zac
  • 813
  • 10
  • 22

1 Answers1

2

You can use the arguments variable inside any function to ensure that the number of actual arguments is not smaller than the number of required arguments.

myFunction: (required1, required2, required3, optional1, optional2) ->
  throw new Error("Given #{arguments.length} out of 3 required.") if arguments.length < 3
  # ...
Community
  • 1
  • 1
fracz
  • 20,536
  • 18
  • 103
  • 149
  • But one more thing, if I wanted to have one of the arguments have a certain type, would there be an easy way to do that? – Zac Jun 26 '16 at 11:28
  • Then you have to check the type in the next line, no magic here. Or you can try [TypeScript](http://www.typescriptlang.org/) instead. – fracz Jun 26 '16 at 13:30