[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 @   Zhentiw  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-11-25 [ARIA] aria-describedby & aria-labelledby
2019-11-25 [Security] Always use parameterized queries
2016-11-25 [Ramda] Handle Branching Logic with Ramda's Conditional Functions
2016-11-25 [Angular2 Router] Setup page title with Router events
2015-11-25 [Redux] Store Methods: getState(), dispatch(), and subscribe()
2015-11-25 [Redux] Introduction
2014-11-25 [AngularJS] Best Practise - Minification and annotation
点击右上角即可分享
微信分享提示