Repeat a given string str(first argument) for num times (second argument). Return an empty string if num is not a positive number. You can also use the built-in .repeat() method or recursion.
function repeatStringNumTimes(str, num) {
return str;
}
repeatStringNumTimes("abc", 3);
This could be done with .repeat() method like so:
if (num < 0) return "";
return str.repeat(num); // would console log abcabcabc;
Also recursion would work here like so;
function repeatStringNumTimes(str, num) {
if (num <= 0) return "";
if (num === 1) return str; //base case
return str + repeatStringNumTimes(str, num - 1);
};
repeatingStringNumTimes("abc", 3);
// "abc" + repeatStringNumTimes("abc", 2)
// "abc" + repeatStringNumTimes("abc", 1)
// "abc"
function repeatStringNumTimes(str, num) {
let final = "";
if (num < 0) return "";
for (let i = 0; i < num; i++) {
final = final + str;
}
return final;
}
console.log(repeatStringNumTimes("abc", 3)); // will display abcabcabc
Top comments (1)
@rthefounding Thank you!
I think you already know, but here are some pretty great solutions, for analysis and your own learning)
forum.freecodecamp.org/t/freecodec...