Skip to content

Commit

Permalink
Discard the state in reservoir() for invalid arguments (#121)
Browse files Browse the repository at this point in the history
Fixes #120
  • Loading branch information
sanmai authored Apr 15, 2023
1 parent 972d478 commit b202232
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
3 changes: 3 additions & 0 deletions src/Standard.php
Original file line number Diff line number Diff line change
Expand Up @@ -778,6 +778,9 @@ public function reservoir(int $size, ?callable $weightFunc = null): array
}

if ($size <= 0) {
// Discard the state to emulate full consumption
$this->pipeline = null;

return [];
}

Expand Down
10 changes: 8 additions & 2 deletions tests/ReservoirTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -158,9 +158,15 @@ public static function provideWeightedInputs(): iterable
*/
public function testWeightedSampleFromGenerator(array $input, int $size, callable $weightFn, array $expected): void
{
$this->assertSame($expected, map(static function () use ($input) {
$pipeline = map(static function () use ($input) {
yield from $input;
})->reservoir($size, $weightFn));
});

$this->assertSame($expected, $pipeline->reservoir($size, $weightFn));

if ($size <= 0) {
$this->assertSame([], $pipeline->toArray());
}
}

/**
Expand Down

0 comments on commit b202232

Please sign in to comment.