Skip to content

Instantly share code, notes, and snippets.

@BideoWego
Created April 30, 2018 22:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BideoWego/799e1ef96563c82d5b247e091818ffea to your computer and use it in GitHub Desktop.
Save BideoWego/799e1ef96563c82d5b247e091818ffea to your computer and use it in GitHub Desktop.
JavaScript chunk array generator example
function * chunkGen(collection, size=2, i=0) {
for (; i < collection.length; i += size) {
yield collection.slice(i, i + size);
}
}
function chunk(collection, size=1) {
const chunked = [];
const gen = chunkGen(collection, size);
let c = gen.next();
while (!c.done) {
chunked.push(c.value);
c = gen.next();
}
return chunked;
}
const result = chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 3);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment