Last active
July 30, 2025 05:23
-
-
Save garyblankenship/7851a1e6276f36925016d8ebe518c4f1 to your computer and use it in GitHub Desktop.
run the closure sometimes, a percentage of the time
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
<?php | |
if (!function_exists('sometimes')) { | |
/** | |
* Executes a callback a given percentage of the time. | |
* | |
* @param int $percentage The percentage of times the callback should run (0-100). | |
* @param callable $callback The closure to execute. | |
* @param mixed|callable|null $default The value to return if the callback is not executed. | |
* If it's a Closure, it will be invoked. | |
* @return mixed The result of the callback if executed, otherwise the default value. | |
*/ | |
function sometimes(int $percentage, callable $callback, $default = null) | |
{ | |
if (random_int(1, 100) <= $percentage) { | |
return $callback(); | |
} | |
return $default instanceof Closure ? $default() : $default; | |
} | |
} | |
// Example Test: | |
$runCount = 0; | |
$totalIterations = 1000000; | |
$percentage = 25; | |
for ($i = 0; $i < $totalIterations; $i++) { | |
if (sometimes($percentage, fn() => true)) { | |
$runCount++; | |
} | |
} | |
echo "The callback was executed approximately " . ($runCount / $totalIterations) * 100 . "% of the time."; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment