How do I write an arrow function in ES6 recursively?

后端 未结 12 924
南旧
南旧 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:21

    i think the simplest solution is looking at the only thing that you don't have, which is a reference to the function itself. because if you have that then recusion is trivial.

    amazingly that is possible through a higher order function.

    let generateTheNeededValue = (f, ...args) => f(f, ...args);
    

    this function as the name sugests, it will generate the reference that we'll need. now we only need to apply this to our function

    (generateTheNeededValue)(ourFunction, ourFunctionArgs)
    

    but the problem with using this thing is that our function definition needs to expect a very special first argument

    let ourFunction = (me, ...ourArgs) => {...}
    

    i like to call this special value as 'me'. and now everytime we need recursion we do like this

    me(me, ...argsOnRecursion);
    

    with all of that. we can now create a simple factorial function.

    ((f, ...args) => f(f, ...args))((me, x) => {
      if(x < 2) {
        return 1;
      } else {
        return x * me(me, x - 1);
      }
    }, 4)
    
    -> 24
    

    i also like to look at the one liner of this

    ((f, ...args) => f(f, ...args))((me, x) => (x < 2) ? 1 : (x * me(me, x - 1)), 4)
    

提交回复
热议问题