Typescript類型體操 - Chunk

題目

中文

你知道 lodash 嗎? lodash中有一個非常實用的方法Chunk, 讓我們實現它吧.
Chunk<T, N>接受兩個泛型參數, 其中 T 是 tuple 類型, N是大於 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]]

English

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

答案

type Chunk<
    T extends any[],
    N extends number,
    S extends any[] = [],
    ALL extends any[] = []
> = T extends [infer L, ...infer R]
    ? S['length'] extends N
        ? Chunk<T, N, [], [...ALL, S]>
        : Chunk<R, N, [...S, L], ALL>
    : S['length'] extends 0
    ? []
    : [...ALL, S];

在線演示

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章