Open yunliuyan opened 1 year ago
建立一个临时数组Temp,用来储存chunk后的数组。
type Chunk<T extends any[], N extends number, Temp extends any[] = []> =
Temp['length'] extends N
? [Temp, ...Chunk<T, N>]
: T extends [infer F, ...infer O]
? Chunk<O, N, [...Temp, F]>
: Temp extends []
? Temp
: [Temp];
type exp1 = Chunk<[1, 2, 3], 1> // expected to be [[1, 2], [3]]
type exp2 = Chunk<[1, 2, 3], 4> // expected to be [[1, 2, 3]]
type exp3 = Chunk<[1, 2, 3], 1> // expected to be [[1], [2], [3]]
type Chunk<T extends any[], N extends number, Arr extends any[] = []> =
Arr['length'] extends N
? [Arr, ...Chunk<T, N>]
: T extends [infer K, ...infer L]
? Chunk<L, N, [...Arr, K]>
: Arr extends [] ? Arr : [Arr]
type exp1 = Chunk<[1, 2, 3], 2> // expected to be [[1, 2], [3]]
type exp2 = Chunk<[1, 2, 3], 4> // expected to be [[1, 2, 3]]
type exp3 = Chunk<[1, 2, 3], 1> // expected to be [[1], [2], [3]]
Chunk
Do you know
lodash
?Chunk
is a very useful function in it, now let's implement it.Chunk<T, N>
accepts two required type parameters, theT
must be atuple
, and theN
must be aninteger >=1