Last active
April 7, 2016 17:35
-
-
Save danrichards/df8e5334d65379dfa6e9090b0dcb4a8f to your computer and use it in GitHub Desktop.
Use dynamic modulo to incrementally splice an array.
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 | |
/** | |
* Provided a threshold, determine modulo to keep every m-th item in the | |
* array where m = ceil(count($array) / $threshold) | |
* | |
* @param $arr | |
* @param $threshold | |
* @param string $round | |
* @param bool $keepLastOverFirst | |
* @return array | |
* @throws InvalidArgumentException | |
*/ | |
public static function moduloSpliceArray(array $arr, $threshold, $round = 'ceil', $keepLastOverFirst = false) | |
{ | |
$round_funcs = ['ceil', 'floor', 'round']; | |
$reduce_func = $keepLastOverFirst ? 'array_pop' : 'array_shift'; | |
$acc_func = $keepLastOverFirst ? 'array_unshift' : 'array_push'; | |
$count = count($arr); | |
if ($count <= $threshold) { | |
return $arr; | |
} | |
if (! in_array($round, $round_funcs)) { | |
throw new InvalidArgumentException('The $round argument should be '.implode(',', $round_funcs)); | |
} | |
$modulo = $round(floatval($count) / $threshold); | |
$arr_modulo = []; | |
$counter = 0; | |
if ($modulo > 1) { | |
while ($item = $reduce_func($arr)) { | |
if (! $counter || $counter % $modulo == 0) { | |
$acc_func($arr_modulo, $item); | |
} | |
$counter++; | |
} | |
} | |
return $arr_modulo; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment