From 6e6d38ac214fecef70ab27a8825cfccdf23ca878 Mon Sep 17 00:00:00 2001 From: Alexey Kopytko Date: Sat, 29 Apr 2023 10:55:54 +0900 Subject: [PATCH] Test it --- src/Standard.php | 23 +++++++++++++++++++++++ tests/CountTest.php | 17 +++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/Standard.php b/src/Standard.php index d9fda55..ccc3e36 100644 --- a/src/Standard.php +++ b/src/Standard.php @@ -547,6 +547,29 @@ public function toArrayPreservingKeys(): array return $this->toArray(true); } + /** + * Counts seen values online. + * + * @param ?int &$count the current count; initialized unless provided + * + * @param-out int $count + * + * @return $this + */ + public function runningCount( + ?int &$count + ): self { + $count ??= 0; + + $this->cast(static function ($input) use (&$count) { + ++$count; + + return $input; + }); + + return $this; + } + /** * {@inheritdoc} * diff --git a/tests/CountTest.php b/tests/CountTest.php index 62d2aeb..ed854ba 100644 --- a/tests/CountTest.php +++ b/tests/CountTest.php @@ -25,6 +25,7 @@ use function Pipeline\fromArray; use function Pipeline\map; use function Pipeline\take; +use function range; /** * @covers \Pipeline\Standard @@ -61,4 +62,20 @@ public function testCountValues(): void yield 2 => 3; })); } + + public function testRunningCount(): void + { + $pipeline = map(fn () => yield from range(0, 100)) + ->runningCount($countAll) + ->filter(fn (int $n) => $n % 2) + ->runningCount($countEvent) + ->filter(fn (int $n) => $n % 3); + + $this->assertSame(0, $countAll); + $this->assertSame(0, $countEvent); + + $this->assertSame(33, $pipeline->count()); + $this->assertSame(101, $countAll); + $this->assertSame(50, $countEvent); + } }