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

25. TrimLeft、Trim、TrimRight #34

Open
astak16 opened this issue Jun 29, 2022 · 0 comments
Open

25. TrimLeft、Trim、TrimRight #34

astak16 opened this issue Jun 29, 2022 · 0 comments
Labels

Comments

@astak16
Copy link
Owner

astak16 commented Jun 29, 2022

题目

题目链接:TrimLeftTrimTrimRight

实现 TrimLeft,满足以下要求

import type { Equal, Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<TrimLeft<'str'>, 'str'>>,
  Expect<Equal<TrimLeft<' str'>, 'str'>>,
  Expect<Equal<TrimLeft<'     str'>, 'str'>>,
  Expect<Equal<TrimLeft<'     str     '>, 'str     '>>,
  Expect<Equal<TrimLeft<'   \n\t foo bar '>, 'foo bar '>>,
  Expect<Equal<TrimLeft<''>, ''>>,
  Expect<Equal<TrimLeft<' \n\t'>, ''>>,
]

答案

方法一

type Space = `${" " | "\t" | "\n"}`;
type TrimLeft<T extends string> = T extends `${Space}${infer R}`
  ? TrimLeft<R>
  : T;

方法二

type TrimLeft<T extends string> = T extends ` ${infer R}`
  ? TrimLeft<R>
  : T extends `\t${infer R}`
  ? TrimLeft<R>
  : T extends `\n${infer R}`
  ? TrimLeft<R>
  : T;

实现 Trim,TrimRight

Trim

type Space = `${" " | "\t" | "\n"}`;
type Trim<T extends string> = T extends
  | `${Space}${infer R}`
  | `${infer R}${Space}`
  ? Trim<R>
  : T;

TrimRight

type Space = `${" " | "\t" | "\n"}`;
type TrimRight<T extends string> = T extends `${infer R}${Space}`
  ? TrimRight<R>
  : T;
@astak16 astak16 added the medium label Jun 29, 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