[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 @   Zhentiw  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-12-15 [Javascript] History API
2020-12-15 [Java Spring MVC] @PathVariable, @Vallidated, @PostMapping & @ResponseStatus
2020-12-15 [Java Spring] @Embeddable and @EmbeddedId
2019-12-15 [Algorithm] 53. Maximum Subarray
2018-12-15 [Algorithm] Breadth First JavaScript Search Algorithm for Graphs
2018-12-15 [Algorithm] JavaScript Graph Data Structure
2017-12-15 [Python] Read and plot data from csv file
点击右上角即可分享
微信分享提示