Skip to content

Commit 03bb80d

Browse files
Add ts filter challenge answer
1 parent e0da8e0 commit 03bb80d

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
18220 - Filter
3+
-------
4+
by Muhun Kim (@x86chi) #medium #array #filter
5+
6+
### Question
7+
8+
Implement the type `Filter<T, Predicate>` takes an Array `T`, primitive type or union primitive type `Predicate` and returns an Array include the elements of
9+
`Predicate`.
10+
11+
> View on GitHub: https://tsch.js.org/18220
12+
*/
13+
14+
/* _____________ Your Code Here _____________ */
15+
16+
// My try
17+
18+
type Filter<T extends any[], P, Acc extends P[] = []> = T extends [infer F, ...infer R]
19+
? F extends P
20+
? Filter<R, P, [...Acc, F]>
21+
: Filter<R, P, Acc>
22+
: Acc
23+
24+
// A simplest option from other programmer (no accummulator)
25+
26+
type Filter2<T extends unknown[], P> = T extends [infer F, ...infer R]
27+
? F extends P
28+
? [F, ...Filter<R, P>]
29+
: Filter<R, P>
30+
: [];
31+
32+
33+
type Testo = Filter<[0, 1, 2], 0 | 1>
34+
// ^? type Testo = [0, 1]
35+
/* _____________ Test Cases _____________ */
36+
import type { Equal, Expect } from '@type-challenges/utils'^M
37+
38+
type Falsy = false | 0 | '' | null | undefined^M
39+
40+
type cases = [
41+
Expect<Equal<Filter<[0, 1, 2], 2>, [2]>>,^M
42+
Expect<Equal<Filter<[0, 1, 2], 0 | 1>, [0, 1]>>,^M
43+
Expect<Equal<Filter<[0, 1, 2], Falsy>, [0]>>,^M
44+
]
45+
46+
/* _____________ Further Steps _____________ */
47+
/*
48+
> Share your solutions: https://tsch.js.org/18220/answer
49+
> View solutions: https://tsch.js.org/18220/solutions
50+
> More Challenges: https://tsch.js.org
51+
*/

0 commit comments

Comments
 (0)