-
Notifications
You must be signed in to change notification settings - Fork 0
/
5140-trunc.ts
44 lines (34 loc) · 1.27 KB
/
5140-trunc.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
/*
5140 - Trunc
-------
by jiangshan (@jiangshanmeta) #medium #template-literal
### Question
Implement the type version of ```Math.trunc```, which takes string or number and returns the integer part of a number by removing any fractional digits.
For example:
```typescript
type A = Trunc<12.34> // 12
```
> View on GitHub: https://tsch.js.org/5140
*/
/* _____________ Your Code Here _____________ */
type Pad<T extends number | string> = `${T}` extends `.${infer Rest}` ? `0.${Rest}` : `${T}`;
type Trunc<T extends number | string> = `${Pad<T>}` extends `${infer N}.${infer Rest}` ? N : `${T}`;
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
type cases = [
Expect<Equal<Trunc<0.1>, '0'>>,
Expect<Equal<Trunc<0.2>, '0'>>,
Expect<Equal<Trunc<1.234>, '1'>>,
Expect<Equal<Trunc<12.345>, '12'>>,
Expect<Equal<Trunc<-5.1>, '-5'>>,
Expect<Equal<Trunc<'.3'>, '0'>>,
Expect<Equal<Trunc<'1.234'>, '1'>>,
Expect<Equal<Trunc<'-10.234'>, '-10'>>,
Expect<Equal<Trunc<10>, '10'>>,
]
/* _____________ Further Steps _____________ */
/*
> Share your solutions: https://tsch.js.org/5140/answer
> View solutions: https://tsch.js.org/5140/solutions
> More Challenges: https://tsch.js.org
*/