projects icon indicating copy to clipboard operation
projects copied to clipboard

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

Open ryo-utsunomiya opened this issue 1 year ago • 0 comments
trafficstars

Bug Report Checklist

  • [X] I have tried restarting my IDE and the issue persists.
  • [X] I have pulled the latest main branch of the repository.
  • [X] I have searched for related issues and found none that matched my issue.
  • [X] This is the appropriate issue form for the bug I would like to report.

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];

ryo-utsunomiya avatar Aug 10 '24 09:08 ryo-utsunomiya