ES6 immediately invoke recursive arrow function

别说谁变了你拦得住时间么 提交于 2019-12-09 08:59:22

问题


This is my current code:

const fn = parameter => {
    // if, else ...
    fn(X);
};
fn(0);

Now, I can't use this approach as I need to call the function with a parameter and it must be callable recursively.

How to refactor the above arrow function to be immediately invoked and recursively callable?


回答1:


First, let me put the disclaimer that Immediately-Invoked-Function-Expressions (IIFE) are considered bad practice in ES6, and this is tail-recursion and personally I would change it to a for loop.

but you can always do this I guess:

((x) =>{ const fn=(p)=>{
       //whatever
       fn(q)
   }
   fn(x)
})(0)



回答2:


JavaScript provides a great solution for recursive functions: named function expressions. Hence I would recommend to use that instead of an arrow function:

(function fn(parameter) {
  // if, else ...
  fn(x);
})(0);



回答3:


If you want to call recursive an lambda expression or anonymous function you need Y combinator. For more details you can read http://mvanier.livejournal.com/2897.html

For factorial it is like

var Y = (proc) => {
  return ((x) => {
    return proc((y) => { return (x(x))(y);});
  })((x) => {
    return proc((y) => { return (x(x))(y);});
  });
};

var factorial = (fact) => {
 return (n) => {
  return (n === 0) ? 1 : n * fact(n-1);
 };
};


console.log( Y(factorial)(5) );

For you code it will be like

const fn = (func)=> {

    return (parameter) => {
       // if else
       func(X);
    }
};

Y(fn)(0);


来源:https://stackoverflow.com/questions/38950857/es6-immediately-invoke-recursive-arrow-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!