String Repeat with Prototype
Write a JavaScript function that extends the String prototype by adding a custom repeat method. The method should accept a number n and return a new string consisting of the original string repeated n times concatenated together.
JavaScript's prototype system allows adding methods to built-in objects like String, Array, and Number. When you add a method to String.prototype, every string instance automatically gains access to that method. This is a powerful feature of JavaScript's prototypal inheritance model that differs from class-based languages.
To implement string repetition, create an empty result array, then loop n times pushing the string into the array, and finally join the array into a single string. Using an array and join is the most efficient approach because string concatenation with + creates many intermediate strings, while the array method collects all parts and joins them once.
Time complexity is O(n * m) where n is the repeat count and m is the original string length. Space complexity is O(n * m) for the result string. The array-based approach is significantly faster than repeated string concatenation for large n values.
Edge cases include n = 0 (return empty string), n = 1 (return the string itself), negative n values (return empty string), and very large n values where the result would exceed available memory. The method should not modify the original string.
Example Input & Output
Repeat ha 2 times
Repeat x 5 times
Repeat once returns same string
Repeat 0 returns empty string
Repeat abc 3 times
Algorithm Flow

Solution Approach
Extend a built-in prototype with a custom method using prototype. Adding methods to prototypes can make code more expressive but should be done cautiously to avoid conflicts.
Modifying built-in prototypes can cause conflicts with libraries and future language features. Consider using utility functions or composition instead of prototype extension.
Time O(n), Space O(n).
Best Answers
function solution(str, n) {
var result = [];
for (var i = 0; i < n; i++) {
result.push(str);
}
return result.join('');
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
