-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
211717e
commit 95330e0
Showing
3 changed files
with
54 additions
and
4 deletions.
There are no files selected for viewing
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
File renamed without changes.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
type BatchOptions = { | ||
limit: number | ||
} | ||
|
||
/** | ||
* TODO: can be faster | ||
*/ | ||
export const batcher = | ||
<T extends any[], K extends keyof T, Item extends T[K]>( | ||
mapper: (item: Item) => Promise<void>, | ||
{ limit = Infinity }: BatchOptions | ||
) => | ||
async (collection: T) => { | ||
const errors: Error[] = [] | ||
const pwindow: Item[] = [] | ||
|
||
const process = async () => { | ||
let batch: any = [] | ||
while (pwindow.length > 0) { | ||
const item = pwindow.shift() | ||
if (item) { | ||
batch.push(mapper(item)) | ||
} | ||
} | ||
const result = await Promise.allSettled(batch) | ||
result.forEach(d => { | ||
if (d.status === 'rejected') { | ||
errors.push(new Error(d.reason)) | ||
} | ||
}) | ||
} | ||
|
||
for (let item of collection) { | ||
pwindow.push(item) | ||
if (pwindow.length >= limit) { | ||
await process() | ||
} | ||
} | ||
|
||
if (pwindow.length) { | ||
await process() | ||
} | ||
|
||
return errors | ||
} |