[Typescript] 44. Medium - Drop char

Drop a specified char from a string.

For example:

type Butterfly = DropChar<' b u t t e r f l y ! ', ' '> // 'butterfly!'

 

/* _____________ Your Code Here _____________ */

type DropChar<S extends string, C extends string, ACC extends string = ''> = S extends `${infer P}${infer REST}` 
  ? P extends C 
    ? DropChar<REST, C, ACC> 
    : `${ACC}${P}${DropChar<REST, C, ACC>}`
  : ACC

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

type cases = [
  // @ts-expect-error
  Expect<Equal<DropChar<'butter fly!', ''>, 'butterfly!'>>,
  Expect<Equal<DropChar<'butter fly!', ' '>, 'butterfly!'>>,
  Expect<Equal<DropChar<'butter fly!', '!'>, 'butter fly'>>,
  Expect<Equal<DropChar<'    butter fly!        ', ' '>, 'butterfly!'>>,
  Expect<Equal<DropChar<' b u t t e r f l y ! ', ' '>, 'butterfly!'>>,
  Expect<Equal<DropChar<' b u t t e r f l y ! ', 'b'>, '  u t t e r f l y ! '>>,
  Expect<Equal<DropChar<' b u t t e r f l y ! ', 't'>, ' b u   e r f l y ! '>>,
]

 

posted @ 2022-10-07 01:08  Zhentiw  阅读(12)  评论(0编辑  收藏  举报