Open yunliuyan opened 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']
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']
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']
Split
![#tuple](https://img.shields.io/badge/-%23tuple-999)
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: