import type {UnwrapBrandedPrimitive} from './unwrap-branded-primitive.d.ts'; import type {IsNumericLiteral} from './is-numeric-literal.d.ts'; import type {IsNegative, PositiveInfinity} from './numeric.d.ts'; import type {DigitCharacter} from './characters.d.ts'; /** Returns a new string which contains the specified number of copies of a given string, just like `String#repeat()`. @example ``` import type {StringRepeat} from 'type-fest'; declare function stringRepeat< S extends string, Count extends number, >(input: S, count: Count): StringRepeat; // The return type is the exact string literal, not just `string`. stringRepeat('foo', 2); //=> 'foofoo' stringRepeat('=', 3); //=> '===' ``` Note: If the specified count has a decimal part, the decimal part will be ignored. @example ``` import type {StringRepeat} from 'type-fest'; type DecimalCount = StringRepeat<'foo', 2.5>; //=> 'foofoo' ``` @category String @category Template literal */ export type StringRepeat = _StringRepeat : S, Count extends object ? UnwrapBrandedPrimitive : Count>; // Brands describe the original values, so all count checks and interpolation operate on unwrapped primitives. type _StringRepeat = Count extends unknown // To distribute `Count` // `String#repeat()` truncates the count toward zero, so counts between -1 and 1 produce an empty string. TypeScript prints magnitudes below `1e-6` in scientific notation, which must be handled before the fallback for large counts. ? `${Count}` extends `-0.${string}` | `${string}e-${string}` ? '' // An infinite count throws before the empty input shortcut. : Count extends PositiveInfinity ? never : IsNegative extends true ? never : S extends '' ? '' : IsNumericLiteral extends false ? string : `${Count}` extends `${string}e${string}` ? string : BuildStringDigitByDigit : never; type BuildStringDigitByDigit = Count extends `${infer First extends DigitCharacter}${infer Rest}` ? BuildStringDigitByDigit< S, Rest, `${RepeatStringTenTimes}${DigitStringRepeat}` > : Accumulator; type RepeatStringTenTimes = `${S}${S}${S}${S}${S}${S}${S}${S}${S}${S}`; // String-keyed lookup avoids building tuple machinery for the digit table. type DigitStringRepeat = { '0': ''; '1': `${S}`; '2': `${S}${S}`; '3': `${S}${S}${S}`; '4': `${S}${S}${S}${S}`; '5': `${S}${S}${S}${S}${S}`; '6': `${S}${S}${S}${S}${S}${S}`; '7': `${S}${S}${S}${S}${S}${S}${S}`; '8': `${S}${S}${S}${S}${S}${S}${S}${S}`; '9': `${S}${S}${S}${S}${S}${S}${S}${S}${S}`; }[Digit]; export {};