Skip to content

Commit ec9b6d8

Browse files
authored
[Feat] Map Array to Single Element Key Value (#161)
* feat: map array to single element key value * refactor: param callback return as array with type
1 parent c5351a9 commit ec9b6d8

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

src/System/Collection/Collection.php

+24
Original file line numberDiff line numberDiff line change
@@ -365,4 +365,28 @@ public function shuffle(): self
365365

366366
return $this->replace($reordered);
367367
}
368+
369+
/**
370+
* Convert array, key and value from item (also key).
371+
*
372+
* @template TKeyItem of array-key
373+
* @template TValueItem
374+
*
375+
* @param callable(TValue, TKey=): array<TKeyItem, TValueItem> $callable With single key/value pair per element
376+
*
377+
* @return $this
378+
*/
379+
public function assocBy(callable $callable): self
380+
{
381+
/** @var array<TKeyItem, TValueItem> */
382+
$new_collection = [];
383+
foreach ($this->collection as $key => $item) {
384+
$array_assoc = call_user_func($callable, $item, $key);
385+
if (array_key_exists(0, $array_assoc) && array_key_exists(1, $array_assoc)) {
386+
$new_collection[$array_assoc[0]] = $array_assoc[1];
387+
}
388+
}
389+
390+
return $this->replace($new_collection);
391+
}
368392
}

tests/Collection/CollectionTest.php

+21
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,27 @@ public function itCanByShuffle()
356356
}
357357
}
358358

359+
/** @test */
360+
public function itCanMapWithKeys()
361+
{
362+
$arr = new Collection([
363+
[
364+
'name' => 'taylor',
365+
'email' => 'taylor@laravel.com',
366+
], [
367+
'name' => 'pradana',
368+
'email' => 'pradana@savanna.com',
369+
],
370+
]);
371+
372+
$assocBy = $arr->assocBy(fn ($item) => [$item['name'], $item['email']]);
373+
374+
$this->assertEquals([
375+
'taylor' => 'taylor@laravel.com',
376+
'pradana' => 'pradana@savanna.com',
377+
], $assocBy->toArray());
378+
}
379+
359380
/** @test */
360381
public function itCanCloneColection()
361382
{

0 commit comments

Comments
 (0)