repeatString - random number exercise

Hello,

I’m really stuck on the repeatString exercise in Web Development 101, and having a tough time with JavaScript in general so far. Specifically I’m stuck in the part where you have to generate ‘hey’ a random number of times. Here’s my code:

const repeatString = function() {
    newString = '';
    number = Math.floor(Math.random() * 1000);

    for (i = number; i < 1000; i++) { 
        newString += 'hey';
    }
return newString;
}

console.log (repeatString());

module.exports = repeatString

My code seems to be generating ‘hey’ a random number of times. I can see it in the console log I’m running with coderunner, but the jasmine test is saying “Expected 579 to equal 973.” - where those two numbers are changing all the time.

It seems like the random number of 'hey’s does not match what the regex is looking for in the spec.js file, and I have no idea how to match the two.

Any help appreciated, thank you!

The random number is generated in the tests. You don’t need to generate it. If your code works for the other tests it should work for the random number. The reason for the random number is to stop people in the function specifically checking for the other numbers in the tests.

What code did you have to pass the other tests?

2 Likes

Thanks for your reply! The code I was using in the first test where ‘hey’ needs to be repeated 3 times was:

const repeatString = function() {
    newString = '';

    for (i = 0; i < 3; i++) { 
        newString += 'hey';
    }
return newString;
}

module.exports = repeatString

For the previous tasks I was usually changing the exit condition of the for loop, or adding an if statement for the negative number ‘ERROR’. All no problem.

Now if I change the exit condition to i < 1000 then all it does of course is repeat ‘hey’ 1000 times.

I don’t “get” how this test is trying to get me to make a random number, or how the jasmine test is going to satisfy itself.

Look at the test cases and do you see anything different on how they call the function?
remember about the parameters.

const repeatString = function(n) {
   // here 'n' could be 3, 10, or 1000
}
1 Like

Because you mentioned parameters I went back on function lessons and realised I didn’t actually understand functions/loops as well as I thought I did. Here’s my new code that’s working fine:

const repeatString = function(string, number) {
    newString = string;

    for (i = 0; i < number-1; i++) { 
        newString += string;
    }
return newString;
}

repeatString('hey', 242);

module.exports = repeatString

Thanks for taking the time to help me. I’ve also realised I was rushing things, so I’m going back through the basics to ensure I understand everything so far correct before moving forward.

1 Like