[Typescript] 111. Hard - String Join

Create a type-safe string join utility which can be used like so:

const hyphenJoiner = join('-')
const result = hyphenJoiner('a', 'b', 'c'); // = 'a-b-c'

Or alternatively:

join('#')('a', 'b', 'c') // = 'a#b#c'

When we pass an empty delimiter (i.e '') to join, we should concat the strings as they are, i.e:

join('')('a', 'b', 'c') // = 'abc'

When only one item is passed, we should get back the original item (without any delimiter added):

join('-')('a') // = 'a'

 

/* _____________ Your Code Here _____________ */
type Join<T extends unknown[], U extends string, ACC extends string = ''> = T extends [infer F extends string, ...infer RT] 
  ? ACC extends ''
    ?  Join<RT, U, `${F}`>
    : Join<RT, U, `${ACC}${U}${F}`>
  : ACC;
declare function join<J extends string>(delimiter: J): <Args extends string[]>(...parts: Args) => Join<Args, J>

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

// Edge cases
const noCharsOutput = join('-')()
const oneCharOutput = join('-')('a')
const noDelimiterOutput = join('')('a', 'b', 'c')

// Regular cases
const hyphenOutput = join('-')('a', 'b', 'c')
const hashOutput = join('#')('a', 'b', 'c')
const twoCharOutput = join('-')('a', 'b')
const longOutput = join('-')('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')

type cases = [
  Expect<Equal<typeof noCharsOutput, ''>>,
  Expect<Equal<typeof oneCharOutput, 'a'>>,
  Expect<Equal<typeof noDelimiterOutput, 'abc'>>,
  Expect<Equal<typeof twoCharOutput, 'a-b'>>,
  Expect<Equal<typeof hyphenOutput, 'a-b-c'>>,
  Expect<Equal<typeof hashOutput, 'a#b#c'>>,
  Expect<Equal<typeof longOutput, 'a-b-c-d-e-f-g-h'>>,
]

 

posted @   Zhentiw  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-11-19 [React] Broadcaster + Operator + Listener pattern -- 20. useBroadcaster & useListener Example
2019-11-19 [Web] Adaptive loading
2015-11-19 [Angular + Webpack] ocLazyLoad compoment
2015-11-19 [Falcor] Retrieving Multiple Values
2014-11-19 [ES6] 05. The leg keyword -- 3. Block Scope
2014-11-19 [ES6] 04. The let keyword -- 2 Fiald case
2014-11-19 [ES6] 03. The let keyword -- 1
点击右上角即可分享
微信分享提示