Created
April 30, 2018 22:44
-
-
Save BideoWego/799e1ef96563c82d5b247e091818ffea to your computer and use it in GitHub Desktop.
JavaScript chunk array generator example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
mm