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?
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.
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.
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.
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.
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With