Skip to content

Commit 7f00a2d

Browse files
authored
Support reverse ranges in LazyCollection::range() (#34191)
1 parent f8cde32 commit 7f00a2d

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

src/Illuminate/Collections/LazyCollection.php

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,14 @@ public function __construct($source = null)
4747
public static function range($from, $to)
4848
{
4949
return new static(function () use ($from, $to) {
50-
for (; $from <= $to; $from++) {
51-
yield $from;
50+
if ($from <= $to) {
51+
for (; $from <= $to; $from++) {
52+
yield $from;
53+
}
54+
} else {
55+
for (; $from >= $to; $from--) {
56+
yield $from;
57+
}
5258
}
5359
});
5460
}

tests/Support/SupportCollectionTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2212,6 +2212,26 @@ public function testRangeMethod($collection)
22122212
[-2, -1, 0, 1, 2],
22132213
$collection::range(-2, 2)->all()
22142214
);
2215+
2216+
$this->assertSame(
2217+
[-4, -3, -2],
2218+
$collection::range(-4, -2)->all()
2219+
);
2220+
2221+
$this->assertSame(
2222+
[5, 4, 3, 2, 1],
2223+
$collection::range(5, 1)->all()
2224+
);
2225+
2226+
$this->assertSame(
2227+
[2, 1, 0, -1, -2],
2228+
$collection::range(2, -2)->all()
2229+
);
2230+
2231+
$this->assertSame(
2232+
[-2, -3, -4],
2233+
$collection::range(-2, -4)->all()
2234+
);
22152235
}
22162236

22172237
/**

0 commit comments

Comments
 (0)