-
-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathreindex.php
47 lines (42 loc) · 1.06 KB
/
reindex.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
declare(strict_types=1);
namespace Psl\Dict;
use Closure;
/**
* Re-indexes an iterable by applying a function to all its values and
* using the returned value as the new key/index.
*
* The function is passed the current iterable value and should return a new
* key for that element. The value is left as-is. The original key is not passed
* to the mapping function.
*
* Examples:
*
* $users = [
* ['id' => 42, 'name' => 'foo'],
* ['id' => 24, 'name' => 'bar']
* ];
*
* Dict\reindex($users, fn($user) => $user['id'])
* => Dict(
* 42 => ['id' => 42, 'name' => 'foo'],
* 24 => ['id' => 24, 'name' => 'bar']
* )
*
* @template Tk1
* @template Tk2 of array-key
* @template Tv
*
* @param iterable<Tk1, Tv> $iterable Iterable to reindex
* @param (Closure(Tv): Tk2) $function
*
* @return array<Tk2, Tv>
*/
function reindex(iterable $iterable, Closure $function): array
{
$result = [];
foreach ($iterable as $value) {
$result[$function($value)] = $value;
}
return $result;
}