Fix off-by-one in `chunk`
chunk(arr, size) to split rows into smaller batches. It looks fine at first glance, but the loop boundary is slightly off: exact divisions can produce an extra empty chunk, and an empty input can come back as [[]]. Fix the bug without changing the function's contract.Solution idea
export default function chunk(arr, size){
if(!Array.isArray(arr) || size <= 0) return [];
const out = [];
// Stop before arr.length so we never push a trailing empty slice.
for(let i = 0; i < arr.length; i += size){
out.push(arr.slice(i, i + size));
}
return out;
}
chunk([1,2,3,4,5], 2) // [[1,2],[3,4],[5]]
chunk([1,2,3,4], 2) // [[1,2],[3,4]]
chunk([], 3) // []Solution
Overview
export default function chunk(arr, size){
if(!Array.isArray(arr) || size <= 0) return [];
const out = [];
// Stop before arr.length so we never push a trailing empty slice.
for(let i = 0; i < arr.length; i += size){
out.push(arr.slice(i, i + size));
}
return out;
}
Similar questions
Guides
Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.