Nishant Srivastava
Nishant Srivastava

Reputation: 449

converting recursive function to arrow function in javascript

How can i convert following function to arrow function? I am using currying here

function mergeString(str){
   return function(str1){
     if(str1){
        return mergeString(str + ' ' + str1); 
     }
     else
     {
       return str;
     }
   }
}

Upvotes: 0

Views: 378

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138267

Actuall this is a good usecase for rest parameters:

 const mergeStrings = (...strings) => strings.join(" ");

Usable as:

mergeString(
  "one",
  "two",
  "three"
)

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386570

You could chain the function heads and then the function body for all.

const mergeString = str => str1 => str1 ? mergeString(str + ' ' + str1) : str;

console.log(mergeString('a')());
console.log(mergeString('a')('b')('c')());
console.log(mergeString('this')('should')('work')('as')('well')());

Upvotes: 4

Related Questions