Created
June 12, 2023 16:13
-
-
Save bricejulia/05d7a93ad46494ba0af1fc29df556f07 to your computer and use it in GitHub Desktop.
batch function
This file contains 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
<?php | |
function batch( | |
iterable $items, | |
callable $exec, | |
?callable $flush = null, | |
int $batchSize = 20, | |
): void | |
{ | |
$current = 0; | |
foreach ($items as $item) { | |
$exec($item); | |
$current++; | |
if ($current % $batchSize === 0) { | |
if ($flush) { | |
$flush($current); | |
} | |
} | |
} | |
if ($flush) { | |
$flush($current); | |
} | |
} | |
batch( | |
items: [4, 3, 2, 1], | |
exec: fn(int $item) => var_dump('handling item', $item), | |
flush: fn(int $index) => var_dump('flush at index', $index), | |
batchSize: 2 | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment