-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathbatch.ts
More file actions
28 lines (24 loc) · 736 Bytes
/
batch.ts
File metadata and controls
28 lines (24 loc) · 736 Bytes
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
import { assert } from "./except.ts";
/**
* Takes a `list` and returns it in multiple smaller lists of the size
* `batchSize`.
* The last batch may be smaller than `batchSize` depending on if `list` size is
* divisible by `batchSize`.
*
* @example
* ```
* batch([1,2,3,4,5], 2) // -> [ [1,2], [3,4], [5] ]
* ```
*/
const batch = <T>(list: T[], batchSize: number): T[][] => {
assert(
typeof batchSize === "number" && !Number.isNaN(batchSize) && batchSize > 0,
"batch size must be > 0",
RangeError,
);
const size = Number.isFinite(batchSize) ? batchSize : list.length;
return [...Array(Math.ceil(list.length / size))].map((_, i) =>
list.slice(i * size, (i + 1) * size)
);
};
export default batch;