Batch - API
A primitive to represent a batch of items.
Installation
- npm
- yarn
- pnpm
npm is the default package manager for Node.js, and to where tscommon is published.
Your project is using npm if it has a
Run the following command in your terminal:
Your project is using npm if it has a
package-lock.json
file in its root folder.Run the following command in your terminal:
terminal
npm install @tscommon/batch
Usage
- Synchronous
- Asynchronous
- Chaining
- Predicate
main.ts
import { Batch } from '@tscommon/batch';
const items = [1, 2, 3, 4, 5];
for (const batch of Batch.from(items, 3)) {
console.log(batch);
}
// Output:
// Batch { index: 0, items: [ 1, 2, 3 ] }
// Batch { index: 1, items: [ 4, 5 ] }
main.ts
import { Readable } from 'stream';
import { Batch } from '@tscommon/batch';
async function main(): Promise<void> {
const items = Readable.from([1, 2, 3, 4, 5]);
for await (const batch of Batch.fromAsync(items, 3)) {
console.log(batch);
}
}
main();
// Output:
// Batch { index: 0, items: [ 1, 2, 3 ] }
// Batch { index: 1, items: [ 4, 5 ] }
You can chain operations using Iterator API (Node 22+). Use TypeScript 5.6+ to compile the following code.
main.ts
import { Batch } from '@tscommon/batch';
Batch.from([1, 2, 3, 4, 5], 3).forEach((batch) => {
console.log(batch);
});
// Output:
// Batch { index: 0, items: [ 1, 2, 3 ] }
// Batch { index: 1, items: [ 4, 5 ] }
You can provide a predicate function to control grouping.
main.ts
import { Batch } from '@tscommon/batch';
function isEven(value: number): boolean {
return value % 2 === 0;
}
for (const batch of Batch.from([1, 2, 3, 4, 5], 2, isEven)) {
console.log(batch);
}
// Output:
// Batch { index: 0, items: [ 2, 4 ] }
// Batch { index: 1, items: [ 6, 8 ] }
// Batch { index: 2, items: [ 10 ] }