Skip to content

Commit

Permalink
[11.x] Arr helper map spread (#50474)
Browse files Browse the repository at this point in the history
* Add Arr::mapSpread helper

* Fix

* StyleCI

* Mark as static

* Fix tests

* Slim test
  • Loading branch information
bilfeldt authored Mar 12, 2024
1 parent 9049c8d commit 2cc827a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/Illuminate/Collections/Arr.php
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,24 @@ public static function mapWithKeys(array $array, callable $callback)
return $result;
}

/**
* Run a map over each nested chunk of items.
*
* @template TMapSpreadValue
*
* @param array $array
* @param callable(mixed...): TMapSpreadValue $callback
* @return array<TKey, TMapSpreadValue>
*/
public static function mapSpread(array $array, callable $callback)
{
return static::map($array, function ($chunk, $key) use ($callback) {
$chunk[] = $key;

return $callback(...$chunk);
});
}

/**
* Push an item onto the beginning of an array.
*
Expand Down
15 changes: 15 additions & 0 deletions tests/Support/SupportArrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -733,6 +733,21 @@ public function testMapByReference()
$this->assertEquals(['first' => 'taylor', 'last' => 'otwell'], $data);
}

public function testMapSpread()
{
$c = [[1, 'a'], [2, 'b']];

$result = Arr::mapSpread($c, function ($number, $character) {
return "{$number}-{$character}";
});
$this->assertEquals(['1-a', '2-b'], $result);

$result = Arr::mapSpread($c, function ($number, $character, $key) {
return "{$number}-{$character}-{$key}";
});
$this->assertEquals(['1-a-0', '2-b-1'], $result);
}

public function testPrepend()
{
$array = Arr::prepend(['one', 'two', 'three', 'four'], 'zero');
Expand Down

0 comments on commit 2cc827a

Please sign in to comment.