[Typescript] 29. Medium - ReplaceAll

Implement ReplaceAll<S, From, To> which replace the all the substring From with To in the given string S

For example

type replaced = ReplaceAll<'t y p e s', ' ', ''> // expected to be 'types'

 

/* _____________ Your Code Here _____________ */

type ReplaceAll<S extends string, From extends string, To extends string> = From extends '' 
  ? S
  : S extends `${infer P1}${From}${infer P2}`
    ?`${P1}${To}${ReplaceAll<P2, From, To>}`
    : S



/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
type z =ReplaceAll<'foobarfoobar', 'ob', 'b'>
// fbarfbar
type cases = [
  Expect<Equal<ReplaceAll<'foobar', 'bar', 'foo'>, 'foofoo'>>,
  Expect<Equal<ReplaceAll<'foobar', 'bag', 'foo'>, 'foobar'>>,
  Expect<Equal<ReplaceAll<'foobarbar', 'bar', 'foo'>, 'foofoofoo'>>,
  Expect<Equal<ReplaceAll<'t y p e s', ' ', ''>, 'types'>>,
  Expect<Equal<ReplaceAll<'foobarbar', '', 'foo'>, 'foobarbar'>>,
  Expect<Equal<ReplaceAll<'barfoo', 'bar', 'foo'>, 'foofoo'>>,
  Expect<Equal<ReplaceAll<'foobarfoobar', 'ob', 'b'>, 'fobarfobar'>>,
  Expect<Equal<ReplaceAll<'foboorfoboar', 'bo', 'b'>, 'foborfobar'>>,
  Expect<Equal<ReplaceAll<'', '', ''>, ''>>,
]

 

posted @   Zhentiw  阅读(41)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-09-13 [React] Handle Recoil Asynchronous Selectors using Loadables in React
2020-09-13 [Docker] Create a Docker configuration for a NestJS API
2020-09-13 [Javascript] Joi for validation
2020-09-13 [Machine Learning] Unrolling Parameters
2019-09-13 [React] Add client-side validation to your React forms with Yup
2018-09-13 [TypeScript] Define Custom Type Guard Functions in TypeScript
2018-09-13 [Sqlite3] Sqlite Introduction
点击右上角即可分享
微信分享提示