Skip to content

Commit 81b1664

Browse files
committed
fix loading an extra element when not necessary
1 parent 6f6ca72 commit 81b1664

File tree

4 files changed

+34
-4
lines changed

4 files changed

+34
-4
lines changed

CHANGELOG.md

+6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# Changelog
22

3+
## [Unreleased]
4+
5+
### Fixed
6+
7+
- A lazy `Sequence` would load an extra element that is never used when calling `take`
8+
39
## 5.11.1 - 2025-01-16
410

511
### Fixed

proofs/sequence.php

+20
Original file line numberDiff line numberDiff line change
@@ -413,4 +413,24 @@ static function($assert, $prefix, $suffix) {
413413
);
414414
},
415415
);
416+
417+
yield proof(
418+
'Sequence::lazy()->take() should not load an extra element',
419+
given(
420+
Set\Sequence::of(Set\Type::any()),
421+
),
422+
static function($assert, $values) {
423+
$sequence = Sequence::lazy(function() use ($values) {
424+
yield from $values;
425+
throw new \Exception;
426+
})->take(\count($values));
427+
428+
$assert->not()->throws(
429+
static fn() => $assert->same(
430+
$values,
431+
$sequence->toList(),
432+
),
433+
);
434+
},
435+
);
416436
};

src/Sequence/Lazy.php

+7-3
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,10 @@ public function take(int $size): Implementation
472472

473473
return new self(
474474
static function(RegisterCleanup $register) use ($values, $size): \Generator {
475+
if ($size === 0) {
476+
return;
477+
}
478+
475479
$taken = 0;
476480
// We intercept the registering of the cleanup function here
477481
// because this generator can be stopped when we reach the number
@@ -482,15 +486,15 @@ static function(RegisterCleanup $register) use ($values, $size): \Generator {
482486
$middleware = $register->push();
483487

484488
foreach ($values($middleware) as $value) {
489+
yield $value;
490+
++$taken;
491+
485492
if ($taken >= $size) {
486493
$middleware->cleanup();
487494
$register->pop();
488495

489496
return;
490497
}
491-
492-
yield $value;
493-
++$taken;
494498
}
495499
},
496500
);

tests/SequenceTest.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -1336,7 +1336,7 @@ public function testCallAllCleanupsWhenFlatMappingComposedLazySequences()
13361336
$cleanups = [];
13371337

13381338
$this->assertSame([1, 2], $sequence->take(2)->toList());
1339-
$this->assertSame(['child2', 'parent'], $cleanups);
1339+
$this->assertSame(['child1', 'parent'], $cleanups);
13401340

13411341
$cleanups = [];
13421342

0 commit comments

Comments
 (0)