[Typescript] 116. Hard - Split

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?']

 

/* _____________ Your Code Here _____________ */
type Equal<T, U> = (<P>(x: P) => P extends T ? 1: 2) extends (<P>(x: U) => U extends T ? 1: 2) ? true: false
type Split<S extends string, SEP extends string> = Equal<S, string> extends true
  ? S[]
  : S extends `${infer P}${SEP}${infer RT}`
    ? [P, ...Split<RT, SEP>]
    : S extends ''
      ? SEP extends ''
        ? []
        : [S]
      : [S];

/* _____________ Test Cases _____________ */
import type { Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<Split<'Hi! How are you?', 'z'>, ['Hi! How are you?']>>,
  Expect<Equal<Split<'Hi! How are you?', ' '>, ['Hi!', 'How', 'are', 'you?']>>,
  Expect<Equal<Split<'Hi! How are you?', ''>, ['H', 'i', '!', ' ', 'H', 'o', 'w', ' ', 'a', 'r', 'e', ' ', 'y', 'o', 'u', '?']>>,
  Expect<Equal<Split<'', ''>, []>>,
  Expect<Equal<Split<'', 'z'>, ['']>>,
  Expect<Equal<Split<string, 'whatever'>, string[]>>,
]

 

posted @ 2022-11-25 15:15  Zhentiw  阅读(25)  评论(0)    收藏  举报