type-challenges / type-challenges

Collection of TypeScript type challenges with online judge

Home Page:https://tsch.js.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

21104 - FindAll

sunupupup opened this issue · comments

wrong solution when meet FindAll<'AAAA','AA'>

type StringLength<S, Arr extends any[] = []> = S extends `${string}${infer R}`
  ? StringLength<R, [...Arr, 1]>
  : Arr['length'];

type FindAll<
  T extends string,
  P extends string,
  PreStr = '',
  Ret extends number[] = []
> = P extends ''
  ? []
  : T extends `${infer Head}${P}${infer Tail}`
  ? FindAll<
      Tail,
      P,
      `${PreStr & string}${Head}${P}`,
      [...Ret, StringLength<`${PreStr & string}${Head}`>]
    >
  : Ret;

need to prase char one by one

type FindAll<
 T extends string,
 P extends string,
 PreStrArr extends any[]  =  [],
 Ret extends number[] = []
> = 
P extends ''
 ? []
 : T extends `${string}${infer R1}`
 		? T extends `${P}${infer _}` 
   				? FindAll<R1, P, [...PreStrArr, any], [...Ret, PreStrArr["length"]]>
   				: FindAll<R1, P, [...PreStrArr, any], Ret>
   		: Ret