How do I write an arrow function in ES6 recursively?

后端 未结 12 876
南旧
南旧 2020-12-08 06:36

Arrow functions in ES6 do not have an arguments property and therefore arguments.callee will not work and would anyway not work in strict mode even

12条回答
  •  一整个雨季
    2020-12-08 07:12

    Claus Reinke has given an answer to your question in a discussion on the esdiscuss.org website.

    In ES6 you have to define what he calls a recursion combinator.

     let rec = (f)=> (..args)=> f( (..args)=>rec(f)(..args), ..args )
    

    If you want to call a recursive arrow function, you have to call the recursion combinator with the arrow function as parameter, the first parameter of the arrow function is a recursive function and the rest are the parameters. The name of the recursive function has no importance as it would not be used outside the recursive combinator. You can then call the anonymous arrow function. Here we compute the factorial of 6.

     rec( (f,n) => (n>1 ? n*f(n-1) : n) )(6)
    

    If you want to test it in Firefox you need to use the ES5 translation of the recursion combinator:

    function rec(f){ 
        return function(){
            return f.apply(this,[
                                   function(){
                                      return rec(f).apply(this,arguments);
                                    }
                                ].concat(Array.prototype.slice.call(arguments))
                          );
        }
    }
    

提交回复
热议问题