-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Open
Labels
459answerShare answers/solutions to a questionShare answers/solutions to a questionenin Englishin English
Description
459 - Flatten
Flatten is a reimplementation of Array.flatten from JavaScript's standard library. Something something a monad is like a burrito.
🎥 Video Explanation
🔢 Code
// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'
type A1 = Flatten<[]>;
type B1 = [];
type C1 = Expect<Equal<A1, B1>>;
type A2 = Flatten<[1, 2, 3, 4]>;
type B2 = [1, 2, 3, 4];
type C2 = Expect<Equal<A2, B2>>;
type A3 = Flatten<[1, [2]]>;
type B3 = [1, 2];
type C3 = Expect<Equal<A3, B3>>;
type A4 = Flatten<[1, 2, [3, 4], [[[5]]]]>;
type B4 = [1, 2, 3, 4, 5];
type C4 = Expect<Equal<A4, B4>>;
type A5 = Flatten<[{ foo: 'bar'; 2: 10 }, 'foobar']>;
type B5 = [{ foo: 'bar'; 2: 10 }, 'foobar'];
type C5 = Expect<Equal<A5, B5>>;
// ============= Your Code Here =============
// alternatives to `T extends []`
// - `T['length'] extends 0`
type Flatten<T> =
T extends []
? []
// could be ... on either side
: T extends [infer Head, ...infer Tail]
? [...Flatten<Head>, ...Flatten<Tail>]
: [T];
// ============== Alternatives ==============
type Flatten<
T extends unknown[],
U extends unknown[] = []
> =
T extends [infer Head, ...infer Tail]
? Head extends unknown[]
? Flatten<[...Head, ...Tail], U>
: Flatten<[...Tail], [...U, Head]>
: U;
type Flatten<T extends unknown[]> =
T extends [infer Head, ...infer Tail]
? Head extends unknown[]
? [...Flatten<Head>, ...Flatten<Tail>]
: [Head, ...Flatten<Tail>]
: [];
type Flatten<T extends unknown[] = []> =
T extends [infer F, ...infer R]
? [
...(
F extends unknown[]
? Flatten<F>
: [F]
),
...Flatten<R>
]
: [];➕ More Solutions
For more video solutions to other challenges: see the umbrella list! #21338
Metadata
Metadata
Assignees
Labels
459answerShare answers/solutions to a questionShare answers/solutions to a questionenin Englishin English