This algorithms is very simple, we take a variable and return that variable being repeated certain amount of times. I usually do this example with my students at the very beginning to teach them these simple concepts:

  • for loops
  • string concatenation
  • convert an array into a string
  • recursion

Before we jump straight into the implementation, you should keep in mind that strings are immutable. You can’t edit strings, you will need to create a variable to store the new string.

String concatenation

const repeatStringNumTimes = (str, num) => {
  let result = '';
  for (let i = 0; i < num; i++) {
    result += str;
  }
  return result;
}

Convert an array into a string

const repeatStringNumTimes = (str, num) => {
  let result = [];
  for (let i = 0; i < num; i++) {
    result.push(str);
  }
  return result.join('');
}

repeatStringNumTimes("abc", 3);

Recursion

const repeatStringNumTimes = (str, num) => {
  if (num <= 0) {
    return '';
  }
  return repeatStringNumTimes(str, num - 1) + str;
}

 

Recursion & ternary operator

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