#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).

Loading...

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

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount