Skip to content

Instantly share code, notes, and snippets.

@oddvalue
Last active January 17, 2019 10:04
Show Gist options
  • Save oddvalue/687a8881597ac92bbf3fc2c74444618e to your computer and use it in GitHub Desktop.
Save oddvalue/687a8881597ac92bbf3fc2c74444618e to your computer and use it in GitHub Desktop.
Reduce a collection of numbers to groups of ranges
<?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