-
-
Notifications
You must be signed in to change notification settings - Fork 720
Expand file tree
/
Copy pathstring-repeat.d.ts
More file actions
76 lines (62 loc) · 1.92 KB
/
Copy pathstring-repeat.d.ts
File metadata and controls
76 lines (62 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import type {IsNumericLiteral} from './is-literal.d.ts';
import type {IsNegative} 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<S, Count>;
// 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<S extends string, Count extends number> =
Count extends unknown // To distribute `Count`
? IsNegative<Count> extends true
? never
: S extends ''
? ''
: IsNumericLiteral<Count> extends false
? string
: `${Count}` extends `${string}e${string}`
? string
: BuildStringDigitByDigit<S, `${Count}`>
: never;
type BuildStringDigitByDigit<S extends string, Count extends string, Accumulator extends string = ''> =
Count extends `${infer First extends DigitCharacter}${infer Rest}`
? BuildStringDigitByDigit<
S,
Rest,
`${RepeatStringTenTimes<Accumulator>}${DigitStringRepeat<S, First>}`
>
: Accumulator;
type RepeatStringTenTimes<S extends string> = `${S}${S}${S}${S}${S}${S}${S}${S}${S}${S}`;
type DigitStringRepeat<S extends string, Digit extends DigitCharacter> = [
'',
`${S}`,
`${S}${S}`,
`${S}${S}${S}`,
`${S}${S}${S}${S}`,
`${S}${S}${S}${S}${S}`,
`${S}${S}${S}${S}${S}${S}`,
`${S}${S}${S}${S}${S}${S}${S}`,
`${S}${S}${S}${S}${S}${S}${S}${S}`,
`${S}${S}${S}${S}${S}${S}${S}${S}${S}`,
][Digit];
export {};