0

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;
     }
   }
}
2
  • Why would you want to use an arrow function here? No good reason to use one. Commented Jun 17, 2018 at 9:17
  • Notice that the term "currying" only applies to functions of fixed arity. For varargs functions it's really hard Commented Jun 17, 2018 at 9:18

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Very nice, but what about mergeString() // => "" ?
that need a different ignature of the function.
1

Actuall this is a good usecase for rest parameters:

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

Usable as:

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

1 Comment

@nishant just wanted to show some alternative ways to write this :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.