-
Notifications
You must be signed in to change notification settings - Fork 2
/
string.ts
70 lines (61 loc) · 1.83 KB
/
string.ts
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
// String.split and Array.join, but in the TS typesystem. #typesystem
namespace String {
export type Embeddable = string | number | bigint | boolean | null | undefined
type JoinRest<
Array extends readonly any[],
Joiner extends string = "",
Output extends string = "",
> = Array extends readonly [infer Element, ...infer Rest]
? Element extends Embeddable
? JoinRest<Rest, Joiner, `${Output}${Joiner}${Element}`>
: never
: Output
export type Join<
Array extends readonly any[],
Joiner extends string = "",
> = Array extends []
? ""
: Array extends [infer Element]
? Element extends Embeddable
? `${Element}`
: never
: Array extends [infer Element, ...infer Rest]
? Element extends Embeddable
? `${Element}${JoinRest<Rest, Joiner>}`
: never
: never
export type Split<
Text extends string,
Splitter extends Embeddable,
Arr extends string[] = [],
> = Text extends `${infer First}${Splitter}${infer Rest}`
? Split<Rest, Splitter, [...Arr, First]>
: Splitter extends ""
? Arr
: [...Arr, Text]
export type Character<T extends string> = T extends ""
? [char: undefined, rest: ""]
: T extends `${infer Char}${infer Rest}`
? [char: Char, rest: Rest]
: never
export type Trim<T extends string> = T extends ` ${infer U}`
? Trim<U>
: T extends `\n${infer U}`
? Trim<U>
: T extends `${infer U} `
? Trim<U>
: T extends `${infer U}\n`
? Trim<U>
: T
}
interface String {
split<This extends string, Splitter extends string>(
this: This,
splitter: Splitter,
limit?: number,
): string extends This ? string[] : String.Split<This, Splitter>
trim<This extends string>(
this: This,
): string extends This ? string : String.Trim<This>
}
let testString = "test string".split(" ")