Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 immediately invoke recursive arrow function

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?

like image 350
user3292653 Avatar asked Aug 15 '16 07:08

user3292653


People also ask

Can arrow functions be recursive?

If you want to call a recursive arrow function, you have to call the recursion combinator with the arrow function as parameter, the first parameter of the arrow function is a recursive function and the rest are the parameters.

Can arrow functions be invoked?

An arrow function expression is an anonymous function expression written with the “fat arrow” syntax ( => ). Like traditional function expressions, arrow functions are not hoisted, and so you cannot call them before you declare them.

How do you call an anonymous recursive function?

Anonymous recursion primarily consists of calling "the current function", which results in direct recursion. Anonymous indirect recursion is possible, such as by calling "the caller (the previous function)", or, more rarely, by going further up the call stack, and this can be chained to produce mutual recursion.

What is IFFI in JavaScript?

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The name IIFE is promoted by Ben Alman in his blog.


2 Answers

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);
like image 51
Felix Kling Avatar answered Nov 15 '22 15:11

Felix Kling


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)
like image 29
Reza Avatar answered Nov 15 '22 15:11

Reza