Named functions are called immediately

My friend today asked me an interesting question about how to write immediately called named functions in CoffeeScript without raising a function variable to the outside.

In JavaScript:

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

The best I could think of in CoffeeScript:

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

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

+4
source share
1 answer

You can not. CoffeeScript does not support such things at all , except for the built-in JavaScript:

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

(Indentation is also not allowed). CoffeeScript will also add some semicolons, so do not use it in the context of an expression.

Then again ...

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

(do not do this)

+4
source

Source: https://habr.com/ru/post/1528874/


All Articles