Given a pattern string P and a text string T, implement the type FindAll<T, P> that returns an Array that contains all indices (0-indexed) from T where P matches. Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement FindAll<T, P> which takes a text string T and a pattern string P, and returns an array of all 0-indexed positions in T where P is found as a substring.
Given a pattern string P and a text string T, implement the type FindAll<T, P> that returns an Array that contains all indices (0-indexed) from T where P matches.
Change the following code to make the test cases pass (no type check errors).
Launch price: $19 $29
One-time payment. Lifetime access to all pro challenges.
We iterate through the string one character at a time, checking at each position whether the pattern matches at that index. We use a counter tuple to track the current index.
type FindAll<
T extends string,
P extends string,
Index extends any[] = []
> = P extends ''
? []
: T extends `${infer _First}${infer Rest}`
? T extends `${P}${string}`
? [Index['length'], ...FindAll<Rest, P, [...Index, 1]>]
: FindAll<Rest, P, [...Index, 1]>
: []How it works:
P extends '' handles the edge case of an empty pattern, returning an empty arrayT extends `${infer _First}${infer Rest}` destructures the string to advance one character at a timeT extends `${P}${string}` checks whether the current position in T starts with the pattern PIndex['length'] (the current position) and continue searching from the next character'AA' in 'AAAA' yields [0, 1, 2]) because we advance by one character regardless of the pattern lengthIndex tuple grows by one element each step, so its length always reflects the current positionThis challenge helps you understand template literal type pattern matching with index tracking and how to apply this concept in real-world scenarios.
This challenge is originally from here.
Get the latest TypeScript tips, tutorials, and updates delivered straight to your inbox.