[Typescript Challenges] 28. Medium - Replace

Implement Replace<S, From, To> which replace the string From with To once in the given string S

For example

type replaced = Replace<'types are fun!', 'fun', 'awesome'> // expected to be 'types are awesome!'

 

/* _____________ Your Code Here _____________ */

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

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

type cases = [
  Expect<Equal<Replace<'foobar', 'bar', 'foo'>, 'foofoo'>>,
  Expect<Equal<Replace<'foobarbar', 'bar', 'foo'>, 'foofoobar'>>,
  Expect<Equal<Replace<'foobarbar', '', 'foo'>, 'foobarbar'>>,
  Expect<Equal<Replace<'foobarbar', 'bar', ''>, 'foobar'>>,
  Expect<Equal<Replace<'foobarbar', 'bra', 'foo'>, 'foobarbar'>>,
  Expect<Equal<Replace<'', '', ''>, ''>>,
]

You can also check whether From is '' in the first place.

type Replace<S extends string, From extends string, To extends string> =
    From extends '' ? S : S extends `${infer A}${From}${infer B}` ? `${A}${To}${B}` : S;

 

posted @ 2022-09-12 16:13  Zhentiw  阅读(23)  评论(0编辑  收藏  举报