Slice
提出詳細
type Blank<N extends number, _A extends unknown[] = []> = _A["length"] extends N ? _A : Blank<N, [..._A, unknown]> type IsNegative<N extends number> = `${N}` extends `-${number}` ? true : false type Absolute<N extends number> = `${N}` extends `-${infer M extends number}` ? M : N type Sub<A extends number, B extends number> = Blank<A> extends [...Blank<B>, ...infer R] ? R["length"] : never type Index<Len extends number, I extends number> = IsNegative<I> extends false ? I : Sub<Len, Absolute<I>> type Slice<Arr extends unknown[], Start extends number = 0, End extends number = Arr["length"]> = Arr extends [...Blank<Index<Arr["length"], End>>, ...infer R1] ? Arr extends [...Blank<Index<Arr["length"], Start>>, ...infer R2, ...R1] ? R2 : [] : []
提出日時 | 2024-09-13 15:18:14 |
---|---|
問題 | Slice |
ユーザー | ookkoouu |
ステータス | Accepted |
import type { Equal, Expect } from '@type-challenges/utils' type Arr = [1, 2, 3, 4, 5] type cases = [ // basic Expect<Equal<Slice<Arr, 0, 1>, [1]>>, Expect<Equal<Slice<Arr, 0, 0>, []>>, Expect<Equal<Slice<Arr, 2, 4>, [3, 4]>>, // optional args Expect<Equal<Slice<[]>, []>>, Expect<Equal<Slice<Arr>, Arr>>, Expect<Equal<Slice<Arr, 0>, Arr>>, Expect<Equal<Slice<Arr, 2>, [3, 4, 5]>>, // negative index Expect<Equal<Slice<Arr, 0, -1>, [1, 2, 3, 4]>>, Expect<Equal<Slice<Arr, -3, -1>, [3, 4]>>, // invalid Expect<Equal<Slice<Arr, 10>, []>>, Expect<Equal<Slice<Arr, 1, 0>, []>>, Expect<Equal<Slice<Arr, 10, 20>, []>>, ]