yunliuyan / type-challenges

typescript-challenges
0 stars 2 forks source link

00026-hard-split #26

Open yunliuyan opened 11 months ago

yunliuyan commented 11 months ago

Split hard #string #split #array #tuple

by Andrea Simone Costa @jfet97

Take the Challenge

The well known split() method splits a string into an array of substrings by looking for a separator, and returns the new array. The goal of this challenge is to split a string, by using a separator, but in the type system!

For example:

type result = Split<'Hi! How are you?', ' '>  // should be ['Hi!', 'How', 'are', 'you?']

Back Share your Solutions Check out Solutions
yunliuyan commented 11 months ago

思路

建立缓存temp,用来缓存结果。注意,左右为空值的情况

代码实现

type Split<S extends string, U extends string, Temp extends string[] = []> = 
     S extends '' 
     ? ''
     : S extends `${infer I}${U}${infer O}` 
        ? I extends '' 
           ? Split<O, U, Temp>  
           : O extends '' 
               ? [...Temp, I] 
               : Split<O, U, [...Temp, I]> 
        : S extends ''
          ? Temp 
          : [...Temp, S];

type result = Split<'Hi! How are you?', ' '>  // should be ['Hi!', 'How', 'are', 'you?']
type result2 = Split<',1,2,3,4,5,6,', ','> // should be ['1', '2', '3', '4', '5', '6']
liangchengv commented 11 months ago
type Split<S extends string, U extends string, T extends string[] = []> = 
S extends '' ? '' : 
S extends `${infer I}${U}${infer L}` ?
I extends '' ? Split<L, U, T> : L extends '' ? [...T, I] : Split<L, U, [...T, I]> : S extends '' ? T : [...T, S];

type result = Split<'Hi! How are you?', ' '>  // should be ['Hi!', 'How', 'are', 'you?']
type result2 = Split<',1,2,3,4,5,6,', ','> // should be ['1', '2', '3', '4', '5', '6']
Janice-Fan commented 11 months ago
type Split<T extends string, P extends string> = 
T extends `${infer X}${P}${infer Y}` ? X extends '' ? Split<Y, P> : [X, ...Split<Y, P>] : T extends '' ? [] : [T];

type result = Split<'Hi! How are you?', ' '>  // should be ['Hi!', 'How', 'are', 'you?']
type result2 = Split<',1,2,3,4,5,6,', ','> // should be ['1', '2', '3', '4', '5', '6']