Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Discard the state in reservoir() for invalid arguments #121

Merged
merged 1 commit into from
Apr 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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