spatie / period

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

Getting the periods that are not overlapped #28

Closed dextermb closed 5 years ago

dextermb commented 5 years ago

Hi there,

I've just picked up this package. It seems pretty good. I've ran into an issue where I want the opposite of overlap.

overlap rightly returns what time out of a list of periods overlap with the current period. I want to be able to get what time is not overlapped.

See visual examples below 👇

Overlap
/*
 * A       [========]
 * B                    [==]
 * C                            [=====]
 * CURRENT        [===============]
 *
 * OVERLAP        [=]   [==]    [=]
 */
Clear(?)
/*
 * A       [========]
 * B                    [==]
 * C                            [=====]
 * CURRENT        [===============]
 *
 * CLEAR  [=======]                [===]
 */

What would be the best way to do this, if already implemented?

brendt commented 5 years ago

I would group A, B and C into a collection, and calculate the boundaries. Next you can diff the boundaries with CURRENT:

/**
 * A          [========]
 * B                       [==]
 * C                               [=====]
 *
 * BOUNDARIES [===========================]
 * CURRENT           [===============]
 *
 * DIFF      [=====]                 [===]
 */

$periodCollection = new PeriodCollection(
    $a = Period::make('2019-01-01', '2019-01-05'),
    $b = Period::make('2019-01-10', '2019-01-15'),
    $c = Period::make('2019-01-20', '2019-01-25')
);

$current = Period::make('2019-01-03', '2019-01-23');

$clear = $periodCollection->boundaries()->diff($current);
brendt commented 5 years ago

You're of course free to extend Period and add your own functionality. I don't think we'd add this case a built-in method in the package though.