Created
November 13, 2019 06:32
-
-
Save SoEasy/17981a8b7c0ade262032e761c3cea8ae to your computer and use it in GitHub Desktop.
Based on generators function for correct split array to chunks
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
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