Skip to content

Commit

Permalink
Merge 6e6d38a into f5b16c8
Browse files Browse the repository at this point in the history
  • Loading branch information
sanmai committed Apr 29, 2023
2 parents f5b16c8 + 6e6d38a commit 5aca958
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/Standard.php
Original file line number Diff line number Diff line change
Expand Up @@ -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}
*
Expand Down
17 changes: 17 additions & 0 deletions tests/CountTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
use function Pipeline\fromArray;
use function Pipeline\map;
use function Pipeline\take;
use function range;

/**
* @covers \Pipeline\Standard
Expand Down Expand Up @@ -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);
}
}

0 comments on commit 5aca958

Please sign in to comment.