Skip to content

Commit

Permalink
Merge pull request #116 from EriBloo/main
Browse files Browse the repository at this point in the history
Implement PeriodCollection Union
  • Loading branch information
riasvdv authored Feb 20, 2023
2 parents 610dc0b + 759397e commit e5a4d85
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 0 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,12 @@ Intersects given period with every period within a collection. The result is a n

![](./docs/img/collection-intersect.png)

### `union(): static`

Merges all periods in collection with overlapping ranges.

![](./docs/img/collection-union.png)

---

Finally, there are a few utility methods available on `PeriodCollection` as well:
Expand Down
Binary file added docs/img/collection-union.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
11 changes: 11 additions & 0 deletions src/PeriodCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -200,4 +200,15 @@ public function sort(): PeriodCollection

return $collection;
}

public function union(): PeriodCollection
{
$boundaries = $this->boundaries();

if (!$boundaries) {
return static::make();
}

return static::make($boundaries)->subtract($boundaries->subtract(...$this));
}
}
21 changes: 21 additions & 0 deletions tests/PeriodCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -284,3 +284,24 @@
expect($sorted[2]->equals($periods[2]))->toBeTrue();
expect($sorted[3]->equals($periods[3]))->toBeTrue();
});

it('unions collection', function () {
$collection = new PeriodCollection(
Period::make('2018-01-30', '2018-01-31'),
Period::make('2018-01-30', '2018-02-2'),
Period::make('2018-02-04', '2018-02-05'),
Period::make('2018-02-07', '2018-02-09'),
Period::make('2018-02-12', '2018-02-14'),
Period::make('2018-02-08', '2018-02-13')
);

$unioned = $collection->union();

expect($unioned)->toHaveCount(3);
expect($unioned[0]->start() == $collection[0]->start())->toBeTrue();
expect($unioned[0]->end() == $collection[1]->end())->toBeTrue();
expect($unioned[1]->start() == $collection[2]->start())->toBeTrue();
expect($unioned[1]->end() == $collection[2]->end())->toBeTrue();
expect($unioned[2]->start() == $collection[3]->start())->toBeTrue();
expect($unioned[2]->end() == $collection[4]->end())->toBeTrue();
});

0 comments on commit e5a4d85

Please sign in to comment.