Implementing String.prototype.padEnd in JavaScript
The padEnd() method is a built-in JavaScript string method that pads a string to a specified length by adding padding characters to the end of the string. This is useful for aligning text, creating consistent output formats, and ensuring strings have a minimum length for various processing tasks. Your challenge is to implement this method as an extension to the String.prototype.
Problem Description
You need to implement a function that extends the String.prototype with a padEnd method. This method should take two arguments:
targetLength: The desired length of the resulting string.padString: The string to use for padding. If not provided, defaults to a space (" ").
The padEnd method should return a new string that is the original string padded with the padString until the resulting string's length equals targetLength. If the original string's length is already greater than or equal to targetLength, the original string should be returned unchanged. The padString should be repeated as necessary to fill the padding space. If padString is longer than one character, only the first character of padString should be used for padding.
Key Requirements:
- Extend
String.prototypewith apadEndmethod. - Handle cases where
targetLengthis less than or equal to the original string's length. - Handle cases where
padStringis not provided (default to space). - Handle cases where
padStringis longer than one character (use only the first character). - Return a new string, not modify the original.
Examples
Example 1:
Input: "hello", 10, " "
Output: "hello "
Explanation: The original string "hello" has length 5. We need to add 5 spaces to reach a length of 10.
Example 2:
Input: "world", 5, "*"
Output: "world"
Explanation: The original string "world" has length 5, which is equal to the target length. No padding is needed.
Example 3:
Input: "abc", 8, "xy"
Output: "abcxyxyxy"
Explanation: The original string "abc" has length 3. We need to add 5 characters. Since padString is "xy", we use 'x' for padding. The result is "abcx" (length 4) + "x" (length 5) = "abcx" + "x" + "x" + "x" + "x" = "abcxxxx".
Example 4:
Input: "test", 10
Output: "test "
Explanation: The original string "test" has length 4. The padString defaults to " ". We need to add 6 spaces to reach a length of 10.
Constraints
targetLengthwill be a non-negative integer.padStringwill be a string or undefined.- The input string will be a string.
- The function should be performant for reasonably sized strings (up to a few thousand characters).
Notes
- Remember that you are extending the
String.prototype. - Consider using string concatenation or other efficient string manipulation techniques.
- Pay close attention to edge cases, such as empty strings and zero
targetLength. - The
padStringshould be used cyclically if the padding length exceeds its length. However, for simplicity, only the first character ofpadStringshould be used if it's longer than one character.