896 B
896 B
title, type, tags, author, cover, dateModified
| title | type | tags | author | cover | dateModified | |||
|---|---|---|---|---|---|---|---|---|
| Chunk iterable | snippet |
|
chalarangelo | cave-view | 2021-03-16T22:50:40+02:00 |
Chunks an iterable into smaller arrays of a specified size.
- Use a
for...ofloop over the given iterable, usingArray.prototype.push()to add each new value to the currentchunk. - Use
Array.prototype.lengthto check if the currentchunkis of the desiredsizeandyieldthe value if it is. - Finally, use
Array.prototype.lengthto check the finalchunkandyieldit 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]]