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); + } }