From a32526cf499aca4e131be0ca60200bebb4da975c Mon Sep 17 00:00:00 2001 From: SonyPradana Date: Wed, 3 Jan 2024 17:45:22 +0700 Subject: [PATCH] feat: collection max and min --- .../AbstractCollectionImmutable.php | 20 ++++++++++++ tests/Collection/CollectionImmutableTest.php | 32 +++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/src/System/Collection/AbstractCollectionImmutable.php b/src/System/Collection/AbstractCollectionImmutable.php index e04a486c..f95f1f6d 100644 --- a/src/System/Collection/AbstractCollectionImmutable.php +++ b/src/System/Collection/AbstractCollectionImmutable.php @@ -338,6 +338,26 @@ public function avg(): int return $this->sum() / $this->count(); } + /** + * Find higest value. + * + * @param string|int|null $key + */ + public function max($key = null): int + { + return max(array_column($this->collection, $key)); + } + + /** + * Find lowest value. + * + * @param string|int|null $key + */ + public function min($key = null): int + { + return min(array_column($this->collection, $key)); + } + // array able /** diff --git a/tests/Collection/CollectionImmutableTest.php b/tests/Collection/CollectionImmutableTest.php index 66613021..50eecd76 100644 --- a/tests/Collection/CollectionImmutableTest.php +++ b/tests/Collection/CollectionImmutableTest.php @@ -219,4 +219,36 @@ public function itCanGetLasts() $this->assertEquals([80, 90], $coll->lasts(2)); } + + /** @test */ + public function itCanGetHigest() + { + $coll = new CollectionImmutable([10, 20, 30, 40, 50, 60, 70, 80, 90]); + + $this->assertEquals(90, $coll->max()); + + $coll = new CollectionImmutable([ + ['rank' => 10], + ['rank' => 50], + ['rank' => 90], + ]); + + $this->assertEquals(90, $coll->max('rank')); + } + + /** @test */ + public function itCanGetLowestValue() + { + $coll = new CollectionImmutable([10, 20, 30, 40, 50, 60, 70, 80, 90]); + + $this->assertEquals(10, $coll->min()); + + $coll = new CollectionImmutable([ + ['rank' => 10], + ['rank' => 50], + ['rank' => 90], + ]); + + $this->assertEquals(10, $coll->min('rank')); + } }