Last active
January 17, 2019 10:04
-
-
Save oddvalue/687a8881597ac92bbf3fc2c74444618e to your computer and use it in GitHub Desktop.
Reduce a collection of numbers to groups of ranges
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 | |
/** | |
* Reduce a collection of numbers to groups of ranges | |
* | |
* @example dayRange(collect([1,2,3,5,6,10])) = "1 - 3 & 5 - 6 & 10" | |
* | |
* @param Collection $days | |
* @return string | |
*/ | |
public function numbersToRanges(Collection $numbers) : string | |
{ | |
return $numbers->reduce(function ($groups, $day) { | |
if ($groups->last() && $groups->last()->last() === $day - 1) { | |
$groups->last()[1] = $day; | |
} else { | |
$groups->push(collect([$day])); | |
} | |
return $groups; | |
}, collect())->map->implode(' - ')->implode(' & '); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment