Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

36. KebabCase #45

Open
astak16 opened this issue Jul 21, 2022 · 0 comments
Open

36. KebabCase #45

astak16 opened this issue Jul 21, 2022 · 0 comments
Labels

Comments

@astak16
Copy link
Owner

astak16 commented Jul 21, 2022

题目

题目链接:KebabCase答题

实现 KebabCase,满足下面需求

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<"😎">, "😎">>
];

答案

方法一

type KebabCase<T> = T extends `${infer FirstLetter}${infer RestLetter}`
  ? Rest extends Uncapitalize<Rest>
    ? `${Uncapitalize<FirstLetter>}${KebabCase<RestLetter>}`
    : `${Uncapitalize<FirstLetter>}-${KebabCase<RestLetter>}`
  : T;

知识点

  1. 把字符串拆分成两部分:FirstLetterRestLetter
  2. 这里不在是判断 FirstLetter 部分,而是判断 RestLetter 部分首字母是否大写
  • 看题意,需要把大写字母变成小写,并且在它前面增加 -
  • 如果判断 FirstLetter,那单词首字母大写的话,就会在单词前面添加 - 不符合题意
@astak16 astak16 added the medium label Jul 21, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant