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.
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).
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:
T to chunk, the chunk size N, and an accumulator Current that builds up the current chunk (defaults to an empty tuple)T extends [infer First, ...infer Rest] extracts the first element and the remaining elements from the input tuple[...Current, First]['length'] extends N checks if adding the current element to the accumulator would complete a chunk of size N[...Current, First] as a finished chunk and recursively processes the remaining elements with a fresh accumulatorChunk<Rest, N, [...Current, First]> and continuesCurrent is not empty), it is emitted as the final (potentially smaller) chunk; otherwise an empty tuple is returnedThis 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.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount