type-challenges icon indicating copy to clipboard operation
type-challenges copied to clipboard

216 - Slice with explanation

Open zhaoyao91 opened this issue 2 years ago • 3 comments

// 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
  : []

playground

zhaoyao91 avatar Jan 14 '23 10:01 zhaoyao91

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:

  1. InitialN is a good abstraction to handle both problems of start and end
  2. by using pattern match to extract final substring, we avoid a lot of details
  3. ToPositive is simple to earth by using Slice, while it's absolutely fit and valid in the context of this problem

zhaoyao91 avatar Jan 14 '23 10:01 zhaoyao91

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 =)

Alexsey avatar Jan 18 '23 22:01 Alexsey

So brilliant by using Slice itself to turn an index into a non-negative number. Great work!

JohnLi1999 avatar Apr 25 '23 06:04 JohnLi1999