Array.prototype.map Polyfill
Implement Array.prototype.map from scratch. Master callback signatures, thisArg binding, and sparse-array hole preservation.
JavaScript · Arrays · Polyfills — Pratik Rai ·
Split an array into groups of a fixed size, with whatever is left over in a shorter final group.
Write chunk(arr, size) splitting the array into subarrays of length size.
The final group holds the remainder and may be shorter. A size of zero or less cannot produce groups — return an empty array.
Input:
JSfile.javascript1chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3);
Output:
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]
Seven items in groups of three: two full groups, then one item left over.
slice past the end of an array simply stops, so the short final group needs no special case.A loop that steps by size instead of by one, with slice doing the extraction.
The short final group needs no special case, because slice past the end simply stops at the end.
JSfile.javascript1function chunk(arr, size) { 2 if (size <= 0) return []; 3 const out = []; 4 for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size)); 5 return out; 6}
The input worth thinking about is a size of zero or less. i += 0 never advances, so an unguarded loop hangs forever — the kind of thing that takes down a tab rather than throwing. Decide what it returns and guard before the loop.
slice copies, so the groups are independent of the input array.
Goal: Return groups of the requested size, with a short final group when needed.
slice each iteration. The final slice returns whatever is left, so a short last group needs no special handling.i += 0 never advances — it hangs the tab rather than throwing. Guard it and return an empty array.slice produces new arrays holding the same element references, so the groups are independent containers but the objects inside them are still shared with the input.Continue learning with these related challenges
Implement Array.prototype.map from scratch. Master callback signatures, thisArg binding, and sparse-array hole preservation.
JavaScript · Arrays · Polyfills — Pratik Rai ·
Implement Array.prototype.filter from scratch. The key detail: push the original element, not the boolean result of the predicate.
JavaScript · Arrays · Polyfills — Pratik Rai ·
Implement Array.prototype.flat from scratch with a configurable depth. Default depth is 1, not Infinity.
JavaScript · Arrays · Recursion — Pratik Rai ·
Implement Array.prototype.map from scratch. Master callback signatures, thisArg binding, and sparse-array hole preservation.
JavaScript · Arrays · Polyfills
Pratik Rai ·
Implement Array.prototype.filter from scratch. The key detail: push the original element, not the boolean result of the predicate.
JavaScript · Arrays · Polyfills
Pratik Rai ·
Implement Array.prototype.flat from scratch with a configurable depth. Default depth is 1, not Infinity.
JavaScript · Arrays · Recursion
Pratik Rai ·