diff --git a/docs/array-utils.md b/docs/array-utils.md index 335d556..b9a6d0d 100644 --- a/docs/array-utils.md +++ b/docs/array-utils.md @@ -4,3 +4,13 @@ Splits `array` into an array of arrays, each sub-array being no larger than the provided `chunkSize`, preserving original order of the elements. + +```typescript +async function callChunked( + chunkSize: number, + array: readonly Item[], + processFn: (arrayChunk: Item[]) => Promise, +): Promise +``` + +Splits `array` by passed `chunkSize` and run callback asynchronously for every chunk in a sequential order. diff --git a/src/utils/arrayUtils.spec.ts b/src/utils/arrayUtils.spec.ts index 1cc904f..066cd83 100644 --- a/src/utils/arrayUtils.spec.ts +++ b/src/utils/arrayUtils.spec.ts @@ -1,4 +1,4 @@ -import { chunk } from './arrayUtils' +import { callChunked, chunk } from './arrayUtils' describe('chunk', () => { it('empty array returns empty array', () => { @@ -33,4 +33,13 @@ describe('chunk', () => { [6, 7], ]) }) + it('should call function with chunked array', async () => { + const array = [1, 2, 3, 4, 5] + const myMock = jest.fn() + expect.assertions(3) + myMock.mockReturnValueOnce([1, 2]).mockReturnValueOnce([3, 4]).mockReturnValue([5]) + await callChunked(2, array, async (arrayChunk) => { + expect(arrayChunk).toStrictEqual(await myMock()) + }) + }) }) diff --git a/src/utils/arrayUtils.ts b/src/utils/arrayUtils.ts index 6be98f5..d1334af 100644 --- a/src/utils/arrayUtils.ts +++ b/src/utils/arrayUtils.ts @@ -14,3 +14,14 @@ export function chunk(array: T[], chunkSize: number): T[][] { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return result } + +export async function callChunked( + chunkSize: number, + array: readonly Item[], + processFn: (arrayChunk: Item[]) => Promise, +): Promise { + for (let i = 0; i < array.length; i += chunkSize) { + const arrayChunk = array.slice(i, i + chunkSize) + await processFn(arrayChunk) + } +}