Last active
March 29, 2023 23:02
-
-
Save webinista/11240585 to your computer and use it in GitHub Desktop.
Array.prototype.chunk: Splits an array into an array of smaller arrays containing `groupsize` members
This file contains 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
/* | |
Split an array into chunks and return an array | |
of these chunks. | |
With kudos to github.com/JudeQuintana | |
This is an update example for code I originally wrote 5+ years ago before | |
JavaScript took over the world. | |
Extending native objects like this is now considered a bad practice, so use | |
the stuff between the curly braces and create your own function instead. | |
*/ | |
Array.prototype.chunk = function(groupsize){ | |
var sets = [], chunks, i = 0; | |
chunks = Math.ceil(this.length / groupsize); | |
while(i < chunks){ | |
sets[i] = this.splice(0, groupsize); | |
i++; | |
} | |
return sets; | |
}; |
Here is mine, with generators approch. usefull when you want deal with bunch of data but keep small memory usage. And you can imagine handle an unlimited data flow with it ^^.
function* ennumerate(iterable, offset=0) {
let i = offset;
for (const item of iterable) {
yield [i++, item];
}
}
function* chunkor(iterable, size) {
let chunk = [];
for (const [index, item] of ennumerate(iterable, 1)) {
chunk.push(item);
if (index % size === 0) {
yield chunk;
chunk = [];
}
}
if (chunk.length > 0) yield chunk;
}
/*
> [...chunkor([0,1,2,3,4,6,7,8,9], 2)]
[ [ 0, 1 ], [ 2, 3 ], [ 4, 6 ], [ 7, 8 ], [ 9 ] ]
> [...chunkor([0,1,2,3,4,6,7,8,9], 3)]
[ [ 0, 1, 2 ], [ 3, 4, 6 ], [ 7, 8, 9 ] ]
*/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using currying, to allow partial application: