-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path108-trim.ts
61 lines (51 loc) · 1.51 KB
/
108-trim.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
/**
* 108 - Trim
*
* Implement `Trim<T>` which takes an exact string type and returns a new string with the whitespace from both ends removed.
*
* For example
*
* ```ts
* type trimmed = Trim<' Hello World '> // expected to be 'Hello World'
* ```
*/
/* _____________ Your Code Here _____________ */
type CharsToTrim = ' ' | '\n' | '\t';
type Split<S> = S extends `${infer A}${infer B}`
? [A, ...Split<B>]
: [];
type Join<L extends string[]> = L extends [infer A extends string, ...infer R extends string[]]
? `${A}${Join<R>}`
: '';
type RemoveSpacesAtTheEnd<L extends string[]> = L extends [...infer R extends string[], infer A]
? A extends CharsToTrim
? RemoveSpacesAtTheEnd<R>
: L
: []
type RemoveSpacesAtTheBeginning<L extends string[]> = L extends [infer A, ...infer R extends string[]]
? A extends CharsToTrim
? RemoveSpacesAtTheBeginning<R>
: L
: [];
type Trim<S extends string> =
Join<
RemoveSpacesAtTheBeginning<
RemoveSpacesAtTheEnd<
Split<S>
>
>
>
;
type S = Trim<' hola sss '>
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
type cases = [
Expect<Equal<Trim<'str'>, 'str'>>,
Expect<Equal<Trim<' str'>, 'str'>>,
Expect<Equal<Trim<' str'>, 'str'>>,
Expect<Equal<Trim<'str '>, 'str'>>,
Expect<Equal<Trim<' str '>, 'str'>>,
Expect<Equal<Trim<' \n\t foo bar \t'>, 'foo bar'>>,
Expect<Equal<Trim<''>, ''>>,
Expect<Equal<Trim<' \n\t '>, ''>>,
]