LearningTypeScript / projects

Hands-on real world projects that will help you exercise your knowledge of TypeScript.
https://learningtypescript.com/projects
244 stars 166 forks source link

🐛 Bug: [type-operations/template-literal-type-shenanigans/03-split-on] Incorrect logic in solution #283

Open ryo-utsunomiya opened 3 months ago

ryo-utsunomiya commented 3 months ago

Bug Report Checklist

Expected

SplitOn<"baby", "a"> -> ["b", "by"] SplitOn<"hello my baby", " "> -> ["hello", "my", "baby"]

Actual

The resulting array is in reverse order.

SplitOn<"baby", "a"> -> ["by", "b"] SplitOn<"hello my baby", " "> -> ["baby", "my", "hello"]

Impacted Project

projects/type-operations/template-literal-type-shenanigans/03-split-on/solution.ts

Additional Info

The correct implementation of the SplitOn type would be something like the following:

export type SplitOn<
    Text extends string,
    On extends string,
    Results extends string[] = []
> = Text extends `${infer Prefix}${On}${infer Suffix}`
    ? SplitOn<Suffix, On, [...Results, Prefix]>
    : [...Results, Text];

Alternatively, it could be written more simply like this:

export type SplitOn<
    Text extends string,
    On extends string
> = Text extends `${infer Prefix}${On}${infer Suffix}`
    ? [Prefix, ...SplitOn<Suffix, On>]
    : [Text];