Implementing the String.prototype.repeat Method in JavaScript
The String.prototype.repeat() method is a built-in JavaScript function that produces a new string by concatenating the original string with itself a specified number of times. This challenge asks you to implement this functionality yourself, providing a deeper understanding of string manipulation and algorithm design. Implementing this method is useful for tasks like generating patterns, creating repetitive text elements, or building dynamic strings.
Problem Description
Your task is to implement a repeat method as a function that can be added to the String.prototype. This method should take a single argument, count, which represents the number of times the string should be repeated. The method should return a new string consisting of the original string repeated count times.
Key Requirements:
- The method must be added to the
String.prototype. - The method must accept a single argument,
count, representing the number of repetitions. - The method must return a new string containing the original string repeated
counttimes. - The method should handle invalid input gracefully.
Expected Behavior:
- If
countis a positive integer, the string should be repeated that many times. - If
countis 0, an empty string should be returned. - If
countis negative, an error should be thrown (e.g.,TypeError). - If
countis not an integer, it should be truncated to an integer (e.g.,2.5becomes2). - The method should not modify the original string.
Edge Cases to Consider:
- Empty string input.
- Large repetition counts (consider potential performance implications).
- Non-integer input for
count. - Negative input for
count.
Examples
Example 1:
Input: "abc".repeat(3)
Output: "abcabcabc"
Explanation: The string "abc" is repeated 3 times.
Example 2:
Input: "hello".repeat(0)
Output: ""
Explanation: The string "hello" is repeated 0 times, resulting in an empty string.
Example 3:
Input: "xyz".repeat(-1)
Output: TypeError: count must be a non-negative integer
Explanation: A negative count is invalid and should throw a TypeError.
Example 4:
Input: "test".repeat(2.7)
Output: "testtest"
Explanation: The non-integer count 2.7 is truncated to 2.
Constraints
countmust be a number.- If
countis negative, aTypeErrormust be thrown. - The method should be performant for reasonable repetition counts (e.g., up to 1000). While extreme optimization isn't required, avoid excessively inefficient approaches.
- The returned string should not exceed a reasonable length (e.g., avoid creating strings that consume excessive memory).
Notes
Consider using a loop to concatenate the string repeatedly. Be mindful of potential performance implications when dealing with very large repetition counts. Think about how to handle non-integer input for count in a clear and consistent manner. Remember to add the method to the String.prototype correctly.