String Repeat and Pad
JS Functions
Easy
15 min
strings
polyfills
Implement three string helpers without using String.prototype.repeat, padStart or padEnd. Export repeat as the default export and padStart / padEnd by name.
import repeat, { padStart, padEnd } from './index';
repeat('ab', 3); // 'ababab'
repeat('x', 0); // ''
padStart('5', 3, '0'); // '005'
padStart('abc', 10, '123'); // '1231231abc' (the filler is cut to fit)
padStart('abc', 6); // ' abc' (default filler is a space)
padStart('abcdef', 3, '*'); // 'abcdef' (already long enough)
padEnd('7', 4, '-'); // '7---'
padEnd('abc', 8, 'xy'); // 'abcxyxyx'
padEnd('abc', 6, ''); // 'abc' (empty filler: nothing to pad with)
Signatures
repeat(str: string, count: number): string
padStart(str: string, targetLength: number, padString?: string): string
padEnd(str: string, targetLength: number, padString?: string): string
Requirements
repeat
- Returns
strconcatenatedcounttimes. A non-integercountis truncated toward zero (2.9→2). - Throws a
RangeErrorifcountis negative orInfinity. - Should take O(log count) concatenations, not O(count).
padStart / padEnd
- If
str.length >= targetLength, returnstrunchanged. padStringdefaults to' '. If it's an empty string, returnstrunchanged.- Otherwise add exactly
targetLength - str.lengthcharacters, made by repeatingpadStringand cutting off the end of the filler if it doesn't fit evenly.padStartputs the filler beforestr,padEndafter it.
Follow-up
- Why is the doubling trick in
repeatfaster than a loop, and does it still matter in modern engines? '5'.padStart(3, '0')is a common way to format times. What's theIntlalternative for formatting numbers with leading zeros?
Spotted a mistake or a rights concern? Report an issue