Better solution for "Repeat a String"

Tell us what’s happening:
Is there a better solution for this?
Better recursion would be nice, as recursion seems very tough to me and so I am trying it.

Your code so far


function repeatStringNumTimes(str, num) {
if (num <= 0) {
  return "";
} else {
  str = repeatStringNumTimes(str, num - 1) + str
}

return str
}

console.log(repeatStringNumTimes("abc", 4));

Challenge: Repeat a String Repeat a String

Link to the challenge:

You do not really need the above or the closing bracket }. Instead of reassigning the result of the recursive call to str + str, just return all of it.

Before posting a working solution for comparison purpose, you should try to compare your solution to a solution on the Get a Hint page.

The third solution is basically the same as yours, but uses a ternary expression.

3 Likes
const repeatStringNumTimes = (str, num) => num < 1 ? '' : str + repeatStringNumTimes(str, num-1);

function repeatStringNumTimes(str, num) {
const arr = str.split(’ ');

return num>=0? Array(num).fill(arr).join(’’):’’;
}
repeatStringNumTimes(“abc”, 3);

I believe that nobody come up with this solution , where I turned the string into an array and fill it with num times then join it again .

What I about using a simple loop ?
is it not a good practice ?

function repeatStringNumTimes(str, num) {
  let res = '';
  for(let i = 0 ;i<num;i++){
    res += str;
  }
  return res;
}