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

[12.x] Add step parameter to LazyCollection range method #53473

Merged
merged 3 commits into from
Nov 12, 2024
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
5 changes: 3 additions & 2 deletions src/Illuminate/Collections/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,12 @@ public function __construct($items = [])
*
* @param int $from
* @param int $to
* @param int $step
* @return static<int, int>
*/
public static function range($from, $to)
public static function range($from, $to, $step = 1)
{
return new static(range($from, $to));
return new static(range($from, $to, $step));
}

/**
Expand Down
3 changes: 2 additions & 1 deletion src/Illuminate/Collections/Enumerable.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,10 @@ public static function times($number, ?callable $callback = null);
*
* @param int $from
* @param int $to
* @param int $step
* @return static
*/
public static function range($from, $to);
public static function range($from, $to, $step = 1);

/**
* Wrap the given value in a collection if applicable.
Expand Down
13 changes: 9 additions & 4 deletions src/Illuminate/Collections/LazyCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,17 +75,22 @@ public static function make($items = [])
*
* @param int $from
* @param int $to
* @param int $step
* @return static<int, int>
*/
public static function range($from, $to)
public static function range($from, $to, $step = 1)
{
return new static(function () use ($from, $to) {
if ($step == 0) {
throw new InvalidArgumentException('Step value cannot be zero.');
}

return new static(function () use ($from, $to, $step) {
if ($from <= $to) {
for (; $from <= $to; $from++) {
for (; $from <= $to; $from += abs($step)) {
yield $from;
}
} else {
for (; $from >= $to; $from--) {
for (; $from >= $to; $from -= abs($step)) {
yield $from;
}
}
Expand Down