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

108 - Trim (🎥 Video Explanation and Solution) #22463

@dimitropoulos

Description

@dimitropoulos

108 - Trim

Trim is very similar to yesterday's TrimLeft challenge, except it works on both sides of the string. There is a TrimRight too, but it's much later on.

🎥 Video Explanation

Release Date: 2023-01-26 19:00 UTC

Trim

🔢 Code

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

type A1 = Trim<'str'>;
type B1 = 'str';
type C1 = Expect<Equal<A1, B1>>;

type A2 = Trim<' str'>;
type B2 = 'str';
type C2 = Expect<Equal<A2, B2>>;

type A3 = Trim<'     str'>;
type B3 = 'str';
type C3 = Expect<Equal<A3, B3>>;

type A4 = Trim<'str   '>;
type B4 = 'str';
type C4 = Expect<Equal<A4, B4>>;

type A5 = Trim<'     str     '>;
type B5 = 'str';
type C5 = Expect<Equal<A5, B5>>;

type A6 = Trim<'   \n\t foo bar \t'>;
type B6 = 'foo bar';
type C6 = Expect<Equal<A6, B6>>;

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

type A8 = Trim<' \n\t '>;
type B8 = '';
type C8 = Expect<Equal<A8, B8>>;

// ============= Your Code Here =============
type Whitespace = ' ' | '\n' | '\t';

type TrimLeft<T extends string> =
  T extends `${Whitespace}${infer U}`
  ? TrimLeft<U>
  : T;

type TrimRight<T extends string> =
  T extends `${infer U}${Whitespace}`
  ? TrimRight<U>
  : T;

type Trim<T extends string> = TrimLeft<TrimRight<T>>;

// ============== Alternatives ==============
type Trim<S extends string> =
  S extends
    | `${Whitespace}${infer T}`
    | `${infer T}${Whitespace}`
  ? Trim<T>
  : S;

➕ More Solutions

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    108answerShare 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