-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Open
Labels
3243answerShare answers/solutions to a questionShare answers/solutions to a questionenin Englishin English
Description
3243 - FlattenDepth
In case the previous challenge on Flatten wasn't already hard enough: FlattenDepth takes it to a new level (literally) by allowing you to specify the depth of flattening. Fun times!
🎥 Video Explanation
🔢 Code
// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'
type A1 = FlattenDepth<[]>;
type B1 = [];
type C1 = Expect<Equal<A1, B1>>;
type A2 = FlattenDepth<[1, 2, 3, 4]>;
type B2 = [1, 2, 3, 4];
type C2 = Expect<Equal<A2, B2>>;
type A3 = FlattenDepth<[1, [2]]>;
type B3 = [1, 2];
type C3 = Expect<Equal<A3, B3>>;
type A4 = FlattenDepth<[1, 2, [3, 4], [[[5]]]], 2>;
type B4 = [1, 2, 3, 4, [5]];
type C4 = Expect<Equal<A4, B4>>;
type A5 = FlattenDepth<[1, 2, [3, 4], [[[5]]]]>;
type B5 = [1, 2, 3, 4, [[5]]];
type C5 = Expect<Equal<A5, B5>>;
type A6 = FlattenDepth<[1, [2, [3, [4, [5]]]]], 3>;
type B6 = [1, 2, 3, 4, [5]];
type C6 = Expect<Equal<A6, B6>>;
type A7 = FlattenDepth<[1, [2, [3, [4, [5]]]]], 19260817>;
type B7 = [1, 2, 3, 4, 5];
type C7 = Expect<Equal<A7, B7>>;
// ============= Your Code Here =============
type FlattenOnce<
T extends unknown[],
Acc extends unknown[] = []
> =
T extends [infer Head, ...infer Tail]
? Head extends unknown[]
? FlattenOnce<Tail, [...Acc, ...Head]>
: FlattenOnce<Tail, [...Acc, Head]>
: Acc
type FlattenDepth<
T extends unknown[],
Depth extends number = 1,
Count extends 1[] = []
> =
Count['length'] extends Depth
? T
: FlattenOnce<T> extends T
? T
: FlattenDepth<
FlattenOnce<T>,
Depth,
[...Count, 1]
>;
// ============== Alternatives ==============
type FlattenDepth<
T extends unknown[],
Depth extends number = 1,
Count extends 1[] = []
> =
Count['length'] extends Depth
? T
: T extends [infer Head, ...infer Tail]
? Head extends unknown[]
? [
...FlattenDepth<Head, Depth, [...Count, 1]>,
...FlattenDepth<Tail, Depth, Count>
]
: [
Head,
...FlattenDepth<Tail, Depth, Count>
]
: [];➕ More Solutions
For more video solutions to other challenges: see the umbrella list! #21338
Metadata
Metadata
Assignees
Labels
3243answerShare answers/solutions to a questionShare answers/solutions to a questionenin Englishin English