Typescript類型體操 - FlattenDepth

題目

中文

遞歸將數組展開到指定的深度

示例:

type a = FlattenDepth<[1, 2, [3, 4], [[[5]]]], 2>; // [1, 2, 3, 4, [5]]. flattern 2 times
type b = FlattenDepth<[1, 2, [3, 4], [[[5]]]]>; // [1, 2, 3, 4, [[5]]]. Depth defaults to be 1

English

Recursively flatten array up to depth times.

For example:

type a = FlattenDepth<[1, 2, [3, 4], [[[5]]]], 2>; // [1, 2, 3, 4, [5]]. flattern 2 times
type b = FlattenDepth<[1, 2, [3, 4], [[[5]]]]>; // [1, 2, 3, 4, [[5]]]. Depth defaults to be 1

If the depth is provided, it's guaranteed to be positive integer.

答案

type FlattenDepth<
    T extends any[],
    Depth extends number = 1,
    Acc extends any[] = []
> = T extends [infer L, ...infer R]
    ? L extends any[]
        ? Acc['length'] extends Depth
            ? T
            : [
                  ...FlattenDepth<L, Depth, [any, ...Acc]>,
                  ...FlattenDepth<R, Depth, Acc>
              ]
        : [L, ...FlattenDepth<R, Depth, Acc>]
    : T;

在線演示

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