type-challenges
type-challenges copied to clipboard
216 - Slice with explanation
// if N is negative, convert it to its positive counterpart by the Arr
type ToPositive<N extends number, Arr extends unknown[]> =
`${N}` extends `-${infer P extends number}`
? Slice<Arr, P>['length']
: N
// get the initial N items of Arr
type InitialN<Arr extends unknown[], N extends number, _Acc extends unknown[] = []> =
_Acc['length'] extends N | Arr['length']
? _Acc
: InitialN<Arr, N, [..._Acc, Arr[_Acc['length']]]>
type Slice<Arr extends unknown[], Start extends number = 0, End extends number = Arr['length']> =
InitialN<Arr, ToPositive<End, Arr>> extends [...InitialN<Arr, ToPositive<Start, Arr>>, ...infer Rest]
? Rest
: []
Explanation
Well, this is one of the most elegant solution from all my challenges. It's short while easy for reasoning.
The key points are:
-
InitialN
is a good abstraction to handle both problems of start and end - by using pattern match to extract final substring, we avoid a lot of details
-
ToPositive
is simple to earth by usingSlice
, while it's absolutely fit and valid in the context of this problem
I've looked over all other solutions (I was checking if mine is the best to publish it 😄 ), and yours appeared to be the best of all! You should change the title to tell others who would search for solutions to this problem that they shouldn't even spend time looking at other issues =)
So brilliant by using Slice
itself to turn an index into a non-negative number. Great work!