#21104Medium

FindAll

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.

Challenge Instructions: FindAll

Medium

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.

Loading...

Detailed Explanation

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:

This 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.

Share this challenge

Stay Updated

Get the latest TypeScript tips, tutorials, and updates delivered straight to your inbox.

No spam, unsubscribe at any time.