Introduction
In this lab, we will explore the concept of chunking an iterable into smaller arrays of a specified size using JavaScript. We will implement a function that takes in an iterable and a size parameter and returns an iterable of smaller arrays that contain a maximum of size elements each. This technique can be useful for various applications, such as breaking down large datasets into smaller chunks for processing or optimizing network requests by reducing the amount of data transferred at once.
Chunk Iterable
To chunk an iterable into smaller arrays of a specified size, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use a
for...ofloop over the given iterable, usingArray.prototype.push()to add each new value to the currentchunk. - Check if the current
chunkis of the desiredsizeusingArray.prototype.lengthandyieldthe value if it is. - Check the final
chunkusingArray.prototype.lengthandyieldit if it's non-empty. - Use the following code:
const chunkify = function* (itr, size) {
let chunk = [];
for (const v of itr) {
chunk.push(v);
if (chunk.length === size) {
yield chunk;
chunk = [];
}
}
if (chunk.length) yield chunk;
};
- Use this code to test the function:
const x = new Set([1, 2, 1, 3, 4, 1, 2, 5]);
[...chunkify(x, 2)]; // [[1, 2], [3, 4], [5]]
Summary
Congratulations! You have completed the Chunk Iterable lab. You can practice more labs in LabEx to improve your skills.