diff --git a/src/PeriodCollection.php b/src/PeriodCollection.php index b577901..2ce3619 100644 --- a/src/PeriodCollection.php +++ b/src/PeriodCollection.php @@ -179,4 +179,14 @@ private function overlap(PeriodCollection $others): PeriodCollection return $overlaps; } + + public function unique(): PeriodCollection + { + $uniquePeriods = []; + foreach ($this->periods as $period) { + $uniquePeriods[$period->asString()] = $period; + } + + return new static(...array_values($uniquePeriods)); + } } diff --git a/tests/PeriodCollectionTest.php b/tests/PeriodCollectionTest.php index d76197e..0919d47 100644 --- a/tests/PeriodCollectionTest.php +++ b/tests/PeriodCollectionTest.php @@ -315,4 +315,24 @@ public function it_substracts_empty_period_collection() $this->assertCount(4, $collection); } + + /** @test */ + public function it_filters_duplicate_periods_in_collection() + { + $collection = new PeriodCollection( + Period::make('2018-01-01', '2018-01-02'), + Period::make('2018-01-01', '2018-01-02'), + Period::make('2018-01-01', '2018-01-02'), + Period::make('2018-01-01', '2018-01-02'), + Period::make('2018-01-01', '2018-01-02'), + Period::make('2018-01-30', '2018-01-31') + ); + + $unique = $collection->unique(); + + $this->assertCount(6, $collection); + $this->assertCount(2, $unique); + $this->assertTrue($unique[0]->equals($collection[0])); + $this->assertTrue($unique[1]->equals($collection[5])); + } }