All files / streams / unstable_batch_stream.ts

100.00% Branches 8/8
100.00% Functions 3/3
100.00% Lines 23/23
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x3
 
 
 
 
 
 
x3
x16
x5
x5
 
x5
x11
x11
x11
x140
x140
x34
x34
x34
x11
x11
x10
x5
x5
x10
x11
x16
x3



















































































// Copyright 2018-2026 the Deno authors. MIT license.
// This module is browser compatible.

/**
 * A {@linkcode TransformStream} that groups input chunks into fixed-size
 * batches. Emits a `T[]` every `size` input chunks and flushes any final
 * non-empty partial batch when the input closes.
 *
 * Input order is preserved.
 *
 * For grouping an in-hand iterable instead of a stream, see
 * {@link https://jsr.io/@std/collections/doc/chunk | `chunk` from `@std/collections`}.
 * For resizing `Uint8Array` chunks at the byte level, see
 * {@linkcode FixedChunkStream}.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @typeParam T The type of the input chunks.
 *
 * @example Batch records for bulk upload
 * ```ts
 * import { BatchStream } from "@std/streams/unstable-batch-stream";
 * import { assertEquals } from "@std/assert";
 *
 * const records = ReadableStream.from([1, 2, 3, 4, 5])
 *   .pipeThrough(new BatchStream(2));
 *
 * assertEquals(await Array.fromAsync(records), [[1, 2], [3, 4], [5]]);
 * ```
 *
 * @example Type inference inside a pipeline
 * ```ts
 * import { BatchStream } from "@std/streams/unstable-batch-stream";
 * import { assertEquals } from "@std/assert";
 *
 * interface User {
 *   id: string;
 * }
 *
 * const users: ReadableStream<User> = ReadableStream.from([
 *   { id: "a" },
 *   { id: "b" },
 *   { id: "c" },
 * ]);
 *
 * const batches: ReadableStream<User[]> = users.pipeThrough(
 *   new BatchStream(2),
 * );
 *
 * assertEquals(await Array.fromAsync(batches), [
 *   [{ id: "a" }, { id: "b" }],
 *   [{ id: "c" }],
 * ]);
 * ```
 */
export class BatchStream<T> extends TransformStream<T, T[]> {
  /**
   * Constructs a new instance.
   *
   * @param size The number of input chunks per emitted batch. Must be a
   * positive integer.
   */
  constructor(size: number) {
    if (!Number.isInteger(size) || size <= 0) {
      throw new RangeError(
        `Cannot construct BatchStream as size must be a positive integer: current value is ${size}`,
      );
    }
    let buffer: T[] = [];
    super({
      transform(chunk, controller) {
        buffer.push(chunk);
        if (buffer.length === size) {
          controller.enqueue(buffer);
          buffer = [];
        }
      },
      flush(controller) {
        if (buffer.length > 0) {
          controller.enqueue(buffer);
        }
      },
    });
  }
}