The challenge this time will have us write a function that takes two arguments, a string and a number. The function should return a single string that contains the original string, repeated the number of times specified by the second argument, or an empty string if the number is negative. A couple examples:
repeat('hi', 4); //-> Should return "hihihihi" repeat('dog', -4); //-> Should return "" (empty string)
First of all, we should check if the number provided as the second argument is lesser than or equal to zero (0), if it is, we can immediatly return and empty string.
function repeat(string, times) { if (times <= 0) { return ''; } }
If the second argument is greater than zero (0), we must concatenate the string with itself as many times as specified and then return the result. For this purpose, I’m going to start by creating a variable where I’ll store the result. I’ll initialize it as an empty string, and will add content to it as necessary. Coincidentally, we can use this variable in the return statement that checks whether the second argument is negative (or zero):
function repeat(string, times) { var resultStr = ''; if (times <= 0) { return resultStr; } for (var i = 1; i <= times; i++) { resultStr += string; } return resultStr; }
As you can see, I used a simple for loop that goes from 0 up to times, each loop adds an instance of the first string to the result string. Then, I return the resulting string at the end of the function.
Try coming up with a shorter version of this function by using the ternary string, or adding a space between each instance of the original string, let’s see how it goes!