-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflat.ts
58 lines (54 loc) · 1.35 KB
/
flat.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
import type { Subtract } from './math/subtract'
/**
* ? HELPER
*
* @internal
*/
type _Internal_Flat_Fork<Tuple, Depth extends number> = Tuple extends any[]
? _Internal_Flat<Tuple, Subtract<Depth, 1>>
: readonly [Tuple]
/**
* ? MUTABLE
*
* @internal
*/
type _Internal_Flat<Tuple extends any[], Depth extends number> = Depth extends 0
? [...Tuple]
: Tuple extends [infer A, ...infer B]
? [..._Internal_Flat_Fork<A, Depth>, ..._Internal_Flat<B, Depth>]
: [...Tuple]
/**
* ? READONLY
*
* @internal
*/
type _Internal_FlatReadonly<
Tuple extends readonly any[],
Depth extends number
> = Depth extends 0
? readonly [...Tuple]
: Tuple extends readonly [infer A, ...infer B]
? readonly [
..._Internal_Flat_Fork<A, Depth>,
..._Internal_FlatReadonly<B, Depth>
]
: readonly [...Tuple]
/**
* Recursively flatten an array up to a given depth.
*
* @param Tuple - The array to flatten.
* @param Depth - The maximum recursion depth.
* @defaultValue 1
* @example
* ```
* type Foo = ['a0', [0, 1], 'a1', [0, ['b0']], 'a2']
* type FooFlatDepth1 = Flat<Foo> // ["a0", 0, 1, "a1", 0, ["b0"], "a2"]
* type FooFlatDepth2 = Flat<Foo, 2> // ["a0", 0, 1, "a1", 0, "b0", "a2"]
* ```
*/
export type Flat<
Tuple extends any[] | readonly any[],
Depth extends number = 1
> = Tuple extends any[]
? _Internal_Flat<Tuple, Depth>
: _Internal_FlatReadonly<Tuple, Depth>