-
-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathpull.php
45 lines (40 loc) · 1 KB
/
pull.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
<?php
declare(strict_types=1);
namespace Psl\Dict;
use Closure;
/**
* Returns a dict where:
* - values are the result of calling `$value_func` on the original value
* - keys are the result of calling `$key_func` on the original value.
*
* Example:
*
* Dict\pull(
* Vec\range(0, 10),
* fn($i) => Str\chr($i + 65),
* fn($i) => 2**$i,
* )
* => Dict(
* 1 => 'A', 2 => 'B', 4 => 'C', 8 => 'D', 16 => 'E', 32 => 'F',
* 64 => 'G', 128 => 'H', 256 => 'I', 512 => 'J', 1024 => 'K'
* )
*
* @template Tk1
* @template Tv1
* @template Tk2 of array-key
* @template Tv2
*
* @param iterable<Tk1, Tv1> $iterable
* @param (Closure(Tv1): Tv2) $value_func
* @param (Closure(Tv1): Tk2) $key_func
*
* @return array<Tk2, Tv2>
*/
function pull(iterable $iterable, Closure $value_func, Closure $key_func): array
{
$result = [];
foreach ($iterable as $value) {
$result[$key_func($value)] = $value_func($value);
}
return $result;
}