Skip to content

Commit

Permalink
feat: Add Number::pairs (#51904)
Browse files Browse the repository at this point in the history
* Add Number::pairs

* formatting

---------

Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
hotmeteor and taylorotwell authored Jun 27, 2024
1 parent 7bf4d41 commit d130cc2
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/Illuminate/Support/Number.php
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,31 @@ public static function clamp(int|float $number, int|float $min, int|float $max)
return min(max($number, $min), $max);
}

/**
* Split the given number into pairs of min/max values.
*
* @param int|float $to
* @param int|float $by
* @param int|float $offset
* @return array
*/
public static function pairs(int|float $to, int|float $by, int|float $offset = 1)
{
$output = [];

for ($lower = 0; $lower < $to; $lower += $by) {
$upper = $lower + $by;

if ($upper > $to) {
$upper = $to;
}

$output[] = [$lower + $offset, $upper];
}

return $output;
}

/**
* Execute the given callback using the given locale.
*
Expand Down
7 changes: 7 additions & 0 deletions tests/Support/SupportNumberTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -286,4 +286,11 @@ public function testSummarize()
$this->assertSame('-1Q', Number::abbreviate(-1000000000000000));
$this->assertSame('-1KQ', Number::abbreviate(-1000000000000000000));
}

public function testPairs()
{
$this->assertSame([[1,10],[11,20],[21,25]], Number::pairs(25, 10));
$this->assertSame([[0,10],[10,20],[20,25]], Number::pairs(25, 10, 0));
$this->assertSame([[0,2.5],[2.5,5.0],[5.0,7.5],[7.5,10.0]], Number::pairs(10, 2.5, 0));
}
}

0 comments on commit d130cc2

Please sign in to comment.