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

459 - Flatten (🎥 Video Explanation and Solution) #22782

@dimitropoulos

Description

@dimitropoulos

459 - Flatten

Flatten is a reimplementation of Array.flatten from JavaScript's standard library. Something something a monad is like a burrito.

🎥 Video Explanation

Release Date: 2023-02-02 19:00 UTC

Flatten

🔢 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

No one assigned

    Labels

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