[Typescript] 37. Medium - KebabCase *

Replace the camelCase or PascalCase string with kebab-case.

FooBarBaz -> foo-bar-baz

For example

type FooBarBaz = KebabCase<"FooBarBaz">;
const foobarbaz: FooBarBaz = "foo-bar-baz";

type DoNothing = KebabCase<"do-nothing">;
const doNothing: DoNothing = "do-nothing";

 

For the First letter, we just need to use lowercase, for the rest, we check if REST is the same as Uncapitalize version of REST, then keep the same, otherwise add '-' in between.

type KebabCase<S> = S extends `${infer First}${infer REST}` 
  ? REST extends Uncapitalize<REST> 
    ? `${Lowercase<First>}${KebabCase<REST>}`
    : `${Lowercase<First>}-${KebabCase<REST>}`
  : S;

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

type cases = [
  Expect<Equal<KebabCase<'FooBarBaz'>, 'foo-bar-baz'>>,
  Expect<Equal<KebabCase<'fooBarBaz'>, 'foo-bar-baz'>>,
  Expect<Equal<KebabCase<'foo-bar'>, 'foo-bar'>>,
  Expect<Equal<KebabCase<'foo_bar'>, 'foo_bar'>>,
  Expect<Equal<KebabCase<'Foo-Bar'>, 'foo--bar'>>,
  Expect<Equal<KebabCase<'ABC'>, 'a-b-c'>>,
  Expect<Equal<KebabCase<'-'>, '-'>>,
  Expect<Equal<KebabCase<''>, ''>>,
  Expect<Equal<KebabCase<'😎'>, '😎'>>,
]

 

posted @ 2022-09-26 03:02  Zhentiw  阅读(18)  评论(0编辑  收藏  举报