ES6 immediately invoke recursive arrow function

前端 未结 3 1478
-上瘾入骨i
-上瘾入骨i 2021-02-13 13:53

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 cal

3条回答
  •  执念已碎
    2021-02-13 14:19

    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);
    

提交回复
热议问题