-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Open
Labels
108answerShare answers/solutions to a questionShare answers/solutions to a questionenin Englishin English
Description
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
🔢 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
Labels
108answerShare answers/solutions to a questionShare answers/solutions to a questionenin Englishin English