spatie / period

Complex period comparisons
https://spatie.be/open-source
MIT License
1.59k stars 72 forks source link

Calculate total length of Collection #25

Closed mstnorris closed 5 years ago

mstnorris commented 5 years ago

Following on from Length with precision and the 2.0 discussion I think it would be useful to be able to call ->length() on a PeriodCollection (with an optional precision) to return the total duration of all the periods contained within, combined. This could be aliased to duration.

Proposed

$collection = new PeriodCollection(
    Period::make('2019-01-01', '2019-01-08'),
    Period::make('2019-02-01', '2019-02-08'),
    Period::make('2019-03-08', '2019-03-15')
);

$collection->length(); // 24 (as the precision of the periods' is DAY
$collection->duration; // 24 as this is another name for length
$collection->length(Precision::HOUR); // 576 (24 days of 24 hours)

Current

This can be achieved by using a Laravel Collection and passing a closure to the sum method but I think this should be part of this package.

$collection = collect([
    Period::make('2019-01-01', '2019-01-08', Precision::HOUR),
    Period::make('2019-02-01', '2019-02-08', Precision::HOUR),
    Period::make('2019-03-08', '2019-03-15', Precision::HOUR)
]);

$collection->sum(function ($p) {
    return $p->length();
}); // 24 (as this does not yet take into account the precision)
jeromegamez commented 5 years ago

@mstnorris Could you have a look at #26 if this might fit your needs?

mstnorris commented 5 years ago

@jeromegamez sorry I had not seen this until now. Thank you! I will play around with it this evening and let you know.

mstnorris commented 5 years ago

@jeromegamez apologies as I have been busy and haven't had a chance to test this out. I will do so this week and come back to you.

mstnorris commented 5 years ago

@jeromegamez I finally got round to testing this and I'm happy to say that it works. Thanks.

brendt commented 5 years ago

We'll try to merge https://github.com/spatie/period/pull/26 soon!