yunliuyan / type-challenges

typescript-challenges
0 stars 2 forks source link

00023-medium-chunk #23

Open yunliuyan opened 1 year ago

yunliuyan commented 1 year ago

Chunk medium #tuple

by キリサメ qianxi @qianxi0410

Take the Challenge

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, the T must be a tuple, and the N must be an integer >=1

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]]

Back Share your Solutions Check out Solutions
yunliuyan commented 1 year ago

思路

建立一个临时数组Temp,用来储存chunk后的数组。

  1. 若Temp的长度与N相等,则将Temp抛出到结果数组中,右边的数组继续递归
  2. 若不相当,将数组T的第一个元素塞入到Temp中,进行递归。
  3. 若T数组遍历完,则返回Temp

代码实现

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]]
Janice-Fan commented 1 year ago
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]]