Repeat a String challenge

Tell us what’s happening:
Hi everybody. Below is my code that doesn’t pass the FCC test. I’ve managed to solve the problem using a ‘while loop’ already and have passed the test. I understand my initial code below is way too complicated for what needs to be done. But it still does the job, I checked it on Codepen. Is it just an issue with an FCC test utility or is there something wrong with my code?

Your code so far

function repeatStringNumTimes(str, num) {
  // repeat after me
  let repeatString = '';
  if (num > 0) {        //make sure the number is positive, otherwise str = ''
    for (let j = 1; j <= num; j++)      //repeat string 'num' number of times
      for (let i = 0; i < str.length; i++) {    //iterate through all characters of the string
        repeatString = repeatString + str[i]
  else { str = '' };
  str = repeatString;
  return str;

repeatStringNumTimes("abc", 3);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:

Hey RomanB your code functionally correct. i have check with different input value and it’s output correctly. code is running fine.

I think the FCC does’t specify the check this type algorithm.

another why are you enter your code ; semicolon at the end of else block . Good Luck.

1 Like

Hey Roman,
You have not put {} for the first for loop.
Otherwise your code runs perfect.

1 Like

I’ve added some comments that might help you work through the logic.

function repeatStringNumTimes(str, num) {
  let repeatString = '';
  if (num > 0) { /* this condition is not necessary.
For any string `str`,  "" is zero repeats of `str`;
and "" is already the value of your `repeatString` variable. */
    for (let j = 1; j <= num; j++) { /* it's simpler and more standard
to start from zero and use greater-than rather than
greater-than-or-equal as the condition */
      for (let i = 0; i < str.length; i++) { /*there's no reason to iterate
through each character of the string. you can just concatenate the whole
string on the end for the same effect. */
        repeatString = repeatString + str[i] //consider using the `+=` operator instead.
  else { str = '' }; /* if `num` is 0, `repeatString` is already "",
so this is redundant. */
  str = repeatString;   // instead of these two lines,
  return str;           // why not just directly return `repeatString`? 

repeatStringNumTimes("abc", 3);
1 Like

Thank you @lionel-rowe for your detailed comments. It took me a while to understand why “if (num>0)” condition is redundant. But I finally got it :slight_smile:
I have finished all the challenges from Basic Algorithm Scripting section of FCC curriculum and I’m pretty sure many of my solutions are too lengthy and not optimal. But I’m not sure if I should find and examine the best solutions.
Thank you once again.