1 Star 1 Fork 0

wangzichu/ts-challenges

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
847.StringJoin.ts 2.06 KB
一键复制 编辑 原始数据 按行查看 历史
王子初 提交于 2023-08-02 16:18 . 更新题库
/*
847 - String Join
-------
by Matt Davis (@tl-matt-davis) #hard
### Question
Create a type-safe string join utility which can be used like so:
```ts
const hyphenJoiner = join('-')
const result = hyphenJoiner('a', 'b', 'c'); // = 'a-b-c'
```
Or alternatively:
```ts
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:
```ts
join('')('a', 'b', 'c') // = 'abc'
```
When only one item is passed, we should get back the original item (without any delimiter added):
```ts
join('-')('a') // = 'a'
```
> View on GitHub: https://tsch.js.org/847
*/
/* _____________ Your Code Here _____________ */
type Test<T extends string[], key extends string, str extends string = T[0]> = T extends [infer R extends string, ...infer F extends string[]] ? Test<F, key, `${str}${key}${R}`> : str
type Test1 = Test<['1', '2'], ','>
declare function join<T extends string[], K extends string>(delimiter: K): (...parts: T) => T extends [infer F extends string, ...infer R] ? 1 : 2
/* _____________ 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'>>,
]
/* _____________ Further Steps _____________ */
/*
> Share your solutions: https://tsch.js.org/847/answer
> View solutions: https://tsch.js.org/847/solutions
> More Challenges: https://tsch.js.org
*/
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/wang-zichu/ts-challenges.git
git@gitee.com:wang-zichu/ts-challenges.git
wang-zichu
ts-challenges
ts-challenges
master

搜索帮助