How do I write an arrow function in ES6 recursively?

后端 未结 12 926
南旧
南旧 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 07:14

    Writing a recursive function without naming it is a problem that is as old as computer science itself (even older, actually, since λ-calculus predates computer science), since in λ-calculus all functions are anonymous, and yet you still need recursion.

    The solution is to use a fixpoint combinator, usually the Y combinator. This looks something like this:

    (y => 
      y(
        givenFact => 
          n => 
            n < 2 ? 1 : n * givenFact(n-1)
      )(5)
    )(le => 
      (f => 
        f(f)
      )(f => 
        le(x => (f(f))(x))
      )
    );
    

    This will compute the factorial of 5 recursively.

    Note: the code is heavily based on this: The Y Combinator explained with JavaScript. All credit should go to the original author. I mostly just "harmonized" (is that what you call refactoring old code with new features from ES/Harmony?) it.

提交回复
热议问题