題目
中文
Fill
是 javascript 中常用的方法, 現在讓我實現類型版本的 Fill
Fill<T, N, Start?, End?>
, 正如你看到的那樣, Fill
接受四個泛型參數, 其中 T
和 N
是必填參數, Start
和 End
是可選參數
這些參數的要求如下: T
必須是一個元組(tuple
), N
可以是任何值類型, Start
和 End
必須是大於或等於 0 的整數
爲了模擬真實的函數, 測試用例包含了一些邊界條件, 我希望你喜歡它 😃
type exp = Fill<[1, 2, 3], 0>; // expected to be [0, 0, 0]
爲了
English
Fill
, a common JavaScript function, now let us implement it with types.
Fill<T, N, Start?, End?>
, as you can see,Fill
accepts four types of parameters, of which T
and N
are required parameters, and Start
and End
are optional parameters.
The requirements for these parameters are: T
must be a tuple
, N
can be any type of value, Start
and End
must be integers greater than or equal to 0.
type exp = Fill<[1, 2, 3], 0>; // expected to be [0, 0, 0]
In order to simulate the real function, the test may contain some boundary conditions, I hope you can enjoy it 😃
答案
type Fill<
T extends unknown[],
N,
Start extends number = 0,
End extends number = T['length'],
Pending extends any[] = [],
Filled extends any[] = []
> = T extends [infer L, ...infer R]
? [
Pending['length'] extends Start
? Filled['length'] extends End
? L
: N
: L,
...Fill<
R,
N,
Start,
End,
Pending['length'] extends Start ? Pending : [...Pending, 0],
Filled['length'] extends End ? Filled : [0, ...Filled]
>
]
: [];