Chunks an iterable into smaller arrays of a specified size.
for...of
loop over the given iterable, using Array.prototype.push()
to add each new value to the current chunk
.Array.prototype.length
to check if the current chunk
is of the desired size
and yield
the value if it is.Array.prototype.length
to check the final chunk
and yield
it if it's non-empty.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;
};
const x = new Set([1, 2, 1, 3, 4, 1, 2, 5]);
[...chunkify(x, 2)]; // [[1, 2], [3, 4], [5]]
Snippet collection
JavaScript generator functions are a more advanced yet very powerful JavaScript ES6 feature, which you can start using in your code right now.
JavaScript, Function
Builds an array, using an iterator function and an initial seed value.
JavaScript, Function
Converts the output of a generator function to an array.
JavaScript, Function
Creates a generator, looping over the given array indefinitely.