这是indexloc提供的服务,不要输入任何密码
Skip to content

612 - KebabCase (🎥 Video Explanation and Solution) #22788

@dimitropoulos

Description

@dimitropoulos

612 - KebabCase

KebabCase may make you hungry, but fear not: it's got nothing to do with food. It's a continuation of a time honored tradition where programmers have to convert between different variable spacing schemes.

🎥 Video Explanation

Release Date: 2023-02-07 19:00 UTC

KebabCase

🔢 Code

// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'

type A1 = KebabCase<'FooBarBaz'>;
type B1 = 'foo-bar-baz';
type C1 = Expect<Equal<A1, B1>>;

type A2 = KebabCase<'fooBarBaz'>;
type B2 = 'foo-bar-baz';
type C2 = Expect<Equal<A2, B2>>;

type A3 = KebabCase<'foo-bar'>;
type B3 = 'foo-bar';
type C3 = Expect<Equal<A3, B3>>;

type A4 = KebabCase<'foo_bar'>;
type B4 = 'foo_bar';
type C4 = Expect<Equal<A4, B4>>;

type A5 = KebabCase<'Foo-Bar'>;
type B5 = 'foo--bar';
type C5 = Expect<Equal<A5, B5>>;

type A6 = KebabCase<'ABC'>;
type B6 = 'a-b-c';
type C6 = Expect<Equal<A6, B6>>;

type A7 = KebabCase<'-'>;
type B7 = '-';
type C7 = Expect<Equal<A7, B7>>;

type A8 = KebabCase<''>;
type B8 = '';
type C8 = Expect<Equal<A8, B8>>;

type A9 = KebabCase<'😎'>;
type B9 = '😎';
type C9 = Expect<Equal<A9, B9>>;

// ============= Your Code Here =============
type KebabCase<T> =
  T extends `${infer Head}${infer Tail}`
  ? Tail extends Uncapitalize<Tail>
    ? `${Uncapitalize<Head>}${KebabCase<Tail>}`
    : `${Uncapitalize<Head>}-${KebabCase<Tail>}`
  : T;

type CapitalLetters = 'A' | 'B' | 'C' | 'F';
type KebabCase<
  T extends string,
  Acc extends string = ''
> =
  T extends `${infer Head}${infer Tail}`
  ? Head extends CapitalLetters
    ? Acc extends ''
      ? KebabCase<Tail, `${Acc}${Lowercase<Head>}`>
      : KebabCase<Tail, `${Acc}-${Lowercase<Head>}`>
    : KebabCase<Tail, `${Acc}${Head}`>
  : Acc;

type KebabCase<T extends string> =
  T extends `${infer Head}${infer Tail}`
  ? `${
      Lowercase<Head>
    }${
      Tail extends Uncapitalize<Tail>
      ? KebabCase<Tail>
      : `-${KebabCase<Tail>}`
    }`
  : T;

➕ More Solutions

For more video solutions to other challenges: see the umbrella list! #21338

Metadata

Metadata

Assignees

No one assigned

    Labels

    612answerShare answers/solutions to a questionenin English

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions