Skip to content

Instantly share code, notes, and snippets.

@SoEasy
Created November 13, 2019 06:32
Show Gist options
  • Save SoEasy/17981a8b7c0ade262032e761c3cea8ae to your computer and use it in GitHub Desktop.
Save SoEasy/17981a8b7c0ade262032e761c3cea8ae to your computer and use it in GitHub Desktop.
Based on generators function for correct split array to chunks
export function* splitArrayToChunks<T>(array: Array<T>, chunkSize: number = Infinity): IterableIterator<Array<T>> {
let resultTasks: Array<T> = [];
for (let i = 0; i < array.length; i += 1) {
const item = array[i];
resultTasks.push(item);
// На последнем элементе если не сделать return -
// генератор завершится только на следующем шаге с пустым массивом
if (i === array.length - 1) {
return resultTasks;
}
if (resultTasks.length === chunkSize) {
yield resultTasks;
resultTasks = [];
}
}
return resultTasks;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment