Siddharth Siddharth - 1 year ago 192
Javascript Question

How do I write an arrow function in ES6 recursively?

Arrow functions in ES6 do not have an

property and therefore
will not work and would anyway not work in strict mode even if just an anonymous function was being used.

Arrow functions cannot be named, so the named functional expression trick can not be used.

So... How does one write a recursive arrow function? That is an arrow function that recursively calls itself based on certain conditions and so on of-course?

Answer Source

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 => 
    givenFact => 
      n => 
        n < 2 ? 1 : n * givenFact(n-1)
)(le => 
  (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.