Last active
April 17, 2025 11:56
-
-
Save egorlepa/80296b5d92917fdf5db260f4e17c2e1b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
func batcher[T any](in chan T, out chan []T, batchSize int, timeout time.Duration) { | |
for { | |
batch := make([]T, 0, batchSize) | |
t := time.After(timeout) | |
for batchReady := false; !batchReady; { | |
select { | |
case e := <-in: | |
batch = append(batch, e) | |
if len(batch) == batchSize { | |
batchReady = true | |
} | |
case <-t: | |
if len(batch) > 0 { | |
batchReady = true | |
break | |
} | |
t = time.After(timeout) | |
} | |
if batchReady == true { | |
out <- batch | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment