[Typescript] 138. Hard - SnakeCase

Create a SnakeCase<T> generic that turns a string formatted in camelCase into a string formatted in snake_case.

A few examples:

type res1 = SnakeCase<"hello">; // => "hello"
type res2 = SnakeCase<"userName">; // => "user_name"
type res3 = SnakeCase<"getElementById">; // => "get_element_by_id"

 

/* _____________ Your Code Here _____________ */

type SnakeCase<T, ACC extends string = ''> = T extends `${infer F}${infer REST}`
  ? Uppercase<F> extends F
    ? SnakeCase<REST, `${ACC}_${Lowercase<F>}`>
    : SnakeCase<REST,`${ACC}${F}`>
  : ACC


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

type cases = [
  Expect<Equal<SnakeCase<'hello'>, 'hello'>>,
  Expect<Equal<SnakeCase<'userName'>, 'user_name'>>,
  Expect<Equal<SnakeCase<'getElementById'>, 'get_element_by_id'>>,
  Expect<Equal<SnakeCase<'getElementById' | 'getElementByClassNames'>, 'get_element_by_id' | 'get_element_by_class_names'>>,
]

 

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