CodingNeed.

Bridge · From syntax to engineering · 25 MIN

Preserve types while batching work

A generic can preserve the item type across a transformation.

A batcher should change grouping without losing the relationship between input and output items. T[] becomes T[][]: each item retains its type. slice copies the array segment so batching does not reorder or remove values from the source. An invalid size must be handled explicitly; a zero increment would otherwise make the loop infinite. These batches define groups only, not a concurrency guarantee. The consumer still decides whether groups run serially and how failures or cancellation propagate.

Write a small contract first, then test how the implementation behaves at its boundaries.

Read the example

const values: number[] = [1, 2, 3];
console.log(JSON.stringify(values.slice(0, 2)));
Check the expected output
[1,2]

Your challenge

Input {items:JSON array,size:integer}. For size <= 0 return []; otherwise return consecutive groups of at most size items. Preserve order and leave the input unchanged.

Solution cost: O(n). time · O(n) for returned array slots; item objects are not deep copied. space

Common trap

splice changes the caller’s array; slice does not.

Further reading: TypeScript generics

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.