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

3243 - FlattenDepth (🎥 Video Explanation and Solution) #24263

@dimitropoulos

Description

@dimitropoulos

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

Release Date: 2023-03-01 19:00 UTC

FlattenDepth

🔢 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

No one assigned

    Labels

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