Fix off-by-one in chunk
chunkeasy
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.Examples
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
1
The fixed code
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.
Open frontend interview questionsBrowse JavaScript interview questionsOpen Essential 60Open Machine Coding HubOpen Frontend Coding ChallengesOpen System DesignOpen Interview Prep GuideOpen System Design BlueprintOpen Framework Prep PathsOpen Study PlansOpen JavaScript mastery study planOpen Company PrepOpen JavaScript Framework Prep Guide
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.