pub fn batch_by_size<T>(
items: Vec<T>,
size_fn: impl Fn(&T) -> usize,
max_size: usize,
) -> Vec<Vec<T>>Expand description
Batch items into groups where the size of each batch is determined by a size function. Ensures no batch exceeds max_size.
ยงExamples
use chie_shared::batch_by_size;
// Batch strings by character count, max 10 chars per batch
let words = vec!["hi", "hello", "world", "rust", "code"];
let batches = batch_by_size(words, |s| s.len(), 10);
// First batch: "hi" (2) + "hello" (5) = 7 chars
// Second batch: "world" (5) + "rust" (4) = 9 chars
// Third batch: "code" (4) chars
assert_eq!(batches.len(), 3);
assert_eq!(batches[0], vec!["hi", "hello"]);
assert_eq!(batches[1], vec!["world", "rust"]);
assert_eq!(batches[2], vec!["code"]);
// Batch numbers by value, max sum of 100
let numbers = vec![30, 40, 50, 20, 60];
let num_batches = batch_by_size(numbers, |n| *n, 100);
assert_eq!(num_batches.len(), 3);
assert_eq!(num_batches[0], vec![30, 40]); // 70 total
assert_eq!(num_batches[1], vec![50, 20]); // 70 total
assert_eq!(num_batches[2], vec![60]); // 60 total