yunliuyan / type-challenges

typescript-challenges
0 stars 2 forks source link

00024-medium-indexof #24

Open yunliuyan opened 10 months ago

yunliuyan commented 10 months ago

IndexOf medium #array

by Pineapple @Pineapple0919

Take the Challenge

Implement the type version of Array.indexOf, indexOf<T, U> takes an Array T, any U and returns the index of the first U in Array T.

type Res = IndexOf<[1, 2, 3], 2>; // expected to be 1
type Res1 = IndexOf<[2,6, 3,8,4,1,7, 3,9], 3>; // expected to be 2
type Res2 = IndexOf<[0, 0, 0], 2>; // expected to be -1

Back Share your Solutions Check out Solutions
yunliuyan commented 10 months ago

思路

创新一个临时数组 Temp,若U和对应T的第一个数组不想当,将T的第一个数组塞入到Temp里面,继续遍历T,直到找到,找到则返回临时数组的长度

代码实现

type IndexOf<T extends any[], U extends any, Temp extends any[] = []> = 
    T extends [infer F, ...infer O] 
    ? F extends U 
       ? Temp['length'] 
        : IndexOf<O, U, [...Temp, F]>
     : -1 
Janice-Fan commented 10 months ago
type IndexOf<T extends any[], P extends any, Arr extends any[] = []> =
 T extends [infer X, ...infer Y] ? X extends P ? Arr['length'] : IndexOf<Y, P, [X, ...Arr]> : -1;

type Res = IndexOf<[1, 2, 3], 2>; // expected to be 1
type Res1 = IndexOf<[2,6, 3,8,4,1,7, 3,9], 3>; // expected to be 2
type Res2 = IndexOf<[0, 0, 0], 2>; // expected to be -1