-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Open
Labels
2070answerShare answers/solutions to a questionShare answers/solutions to a questionenin Englishin English
Description
2070 - Drop Char
DropChar gives us a feel for how to remove things from a string. We've done a lot of addition and splitting to tuples, but knowing how to take away is just as important.
🎥 Video Explanation
🔢 Code
// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'
type A1 = DropChar<'butter fly!', ' '>;
type B1 = 'butterfly!';
type C1 = Expect<Equal<A1, B1>>;
type A2 = DropChar<'butter fly!', '!'>;
type B2 = 'butter fly';
type C2 = Expect<Equal<A2, B2>>;
type A3 = DropChar<' butter fly! ', ' '>;
type B3 = 'butterfly!';
type C3 = Expect<Equal<A3, B3>>;
type A4 = DropChar<' b u t t e r f l y ! ', ' '>;
type B4 = 'butterfly!';
type C4 = Expect<Equal<A4, B4>>;
type A5 = DropChar<' b u t t e r f l y ! ', 'b'>;
type B5 = ' u t t e r f l y ! ';
type C5 = Expect<Equal<A5, B5>>;
type A6 = DropChar<' b u t t e r f l y ! ', 't'>;
type B6 = ' b u e r f l y ! ';
type C6 = Expect<Equal<A6, B6>>;
// @ts-expect-error(2344)
type E1 = Expect<Equal<
// @ts-expect-error(2589)
DropChar<'butter fly!', ''>,
'butterfly!'
>>;
// ============= Your Code Here =============
type DropChar<T, C extends string> =
T extends `${infer Left}${C}${infer Right}`
? DropChar<`${Left}${Right}`, C>
: T
;
// ============== Alternatives ==============
type DropChar<T, C extends string> =
T extends `${infer Left}${C}${infer Right}`
? `${Left}${DropChar<Right, C>}`
: T
;
type DropChar<S, C extends string> =
S extends `${C}${infer R}${C}`
? DropChar<R, C>
: S extends `${C}${infer R}`
? DropChar<R, C>
: S extends `${infer R}${C}`
? DropChar<R, C>
: S extends `${infer A}${C}${infer B}`
? DropChar<`${A}${B}`, C>
: S
// this one manages to pass
// without making `C` extend `string`
type DropChar<S, C> =
S extends `${infer Head}${infer Tail}`
? `${C extends Head ? '' : Head}${DropChar<Tail, C>}`
: ""
type DropChar<S, C> =
S extends `${infer L}${infer R}`
? `${
[L, C] extends [C, L]
? ''
: L
}${DropChar<R, C>}`
: S➕ More Solutions
For more video solutions to other challenges: see the umbrella list! #21338
Metadata
Metadata
Assignees
Labels
2070answerShare answers/solutions to a questionShare answers/solutions to a questionenin Englishin English