#4499Medium

Chunk

Do you know `lodash`? `Chunk` is a very useful function in it, now let's implement it. Learn tuple manipulation in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement Chunk<T, N> which splits a tuple into groups of size N, similar to Lodash's _.chunk function.

Challenge Instructions: Chunk

Medium

Do you know lodash? Chunk is a very useful function in it, now let's implement it. Chunk<T, N> accepts two required type parameters, the T must be a tuple, and the N must be an integer >=1

type exp1 = Chunk<[1, 2, 3], 2> // expected to be [[1, 2], [3]]
type exp2 = Chunk<[1, 2, 3], 4> // expected to be [[1, 2, 3]]
type exp3 = Chunk<[1, 2, 3], 1> // expected to be [[1], [2], [3]]

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
type cases = [
  Expect<Equal<Chunk<[], 1>, []>>,
  Expect<Equal<Chunk<[1, 2, 3], 1>, [[1], [2], [3]]>>,
  Expect<Equal<Chunk<[1, 2, 3], 2>, [[1, 2], [3]]>>,
  Expect<Equal<Chunk<[1, 2, 3, 4], 2>, [[1, 2], [3, 4]]>>,
  Expect<Equal<Chunk<[1, 2, 3, 4], 5>, [[1, 2, 3, 4]]>>,
  Expect<Equal<Chunk<[1, true, 2, false], 2>, [[1, true], [2, false]]>>,
]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

type Chunk<
  T extends any[],
  N extends number,
  Current extends any[] = []
> = T extends [infer First, ...infer Rest]
  ? [...Current, First]['length'] extends N
    ? [[...Current, First], ...Chunk<Rest, N>]
    : Chunk<Rest, N, [...Current, First]>
  : Current extends []
    ? []
    : [Current]

How it works:

This challenge helps you understand recursive tuple partitioning with accumulator patterns, and how to apply these concepts in real-world scenarios.

This challenge is originally from here.

Share this challenge