ghaiklor / type-challenges-solutions

Solutions for the collection of TypeScript type challenges with explanations
https://ghaiklor.github.io/type-challenges-solutions/
Creative Commons Attribution 4.0 International
470 stars 56 forks source link

type-challenges-solutions/ru/medium-replaceall #86

Open utterances-bot opened 2 years ago

utterances-bot commented 2 years ago

ReplaceAll

This project is aimed at helping you better understand how the type system works, writing your own utilities, or just having fun with the challenges.

https://ghaiklor.github.io/type-challenges-solutions/ru/medium-replaceall.html

ghaiklor commented 2 years ago

@froziq пишет:

В песочнице не проходят два кейса (возможно их добавили позже того, как было предоставлено решение тобой)

  Expect<Equal<ReplaceAll<'foobarfoobar', 'ob', 'b'>, 'fobarfobar'>>,
  Expect<Equal<ReplaceAll<'foboorfoboar', 'bo', 'b'>, 'foborfobar'>>,

в них если делать рекурсивно, то будут вырезаны лишние символы:

ReplaceAll<'foobarfoobar', 'ob', 'b'> // = 'fbarfbar' вместо 'fobarfobar'

Предлагаю решение через сохранение уже проверенной части строки и склеивание её с заменяемой частью:

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