[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[]>>,
]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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