I am trying to create a chunking class in typescript, since I keep reusing the same code over and over based on: Split array into chunks
Here is what I have:
export class array_chunk {
arr = [];
chunk: number;
constructor(arr: any, chunk: number) {
this.arr = arr;
this.chunk = chunk;
}
forEachChunk(funct: Function) {
for (let i = 0, j = this.arr.length; i < j; i += this.chunk) {
const temparray = this.arr.slice(i, i + this.chunk);
temparray.forEach((ta: any) => {
funct();
});
}
}
}
/// usage?
let me = new array_chunk([5, 4, 3], 1);
me.forEachChunk((chunkArray: any) => {
console.log(JSON.stringify(chunkArray));
return chunkArray;
});
I can't wrap my head around it it. Basically, I would like something similar to forEach but for the chunks. Then I could forEach that. Am I close? I realize there should be different ways of thinking about this as my example is just conjecture.
EDIT --> here is the SOLUTION code I ended up using thanks to @skovy
class array_chunk {
arr: any[];
chunk: number;
constructor(arr: any[], chunk = 100) {
this.arr = arr;
this.chunk = chunk;
}
forEachChunk(funct: Function) {
for (let i = 0, j = this.arr.length; i < j; i += this.chunk) {
const tempArray = this.arr.slice(i, i + this.chunk);
funct(tempArray);
}
}
}
/// usage
let me = new array_chunk([5, 4, 3, 2, 1, 3, 2, 4], 3);
me.forEachChunk((chunkArray: any[]) => {
console.log("chunk");
chunkArray.forEach((ca) => {
console.log(ca);
})
return chunkArray;
});