knubie
knubie

Reputation: 231

Immediately invoked named functions

A friend of mine posed an interesting question to me today about how to write immediately invoked named functions in CoffeeScript without hoisting the function variable to the outer scope.

In JavaScript:

(function factorial(n) { return n <= 1 ? 1 : n * factorial(n-1); })(5);

The best I could come up with in CoffeeScript:

do -> do factorial = (n = 5) ->
    if n <= 1 then 1 else n * factorial(n-1)

looks a bit awkward. Is there a better way to do this?

Upvotes: 4

Views: 91

Answers (1)

Ry-
Ry-

Reputation: 224867

You can’t. CoffeeScript doesn’t support this kind of thing at all, except via inline JavaScript:

result = `(function factorial(n) {`
return if n <= 1 then 1 else n * factorial(n-1)
`})(5)`

(No indenting allowed, either.) CoffeeScript will insert some semicolons for you, too, so no using it in expression context.

Then again…

-> if n <= 1 then 1 else n * arguments.callee n-1

(don’t do that)

Upvotes: 4

Related Questions