/
mapValues.php
54 lines (48 loc) · 1.61 KB
/
mapValues.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
48
49
50
51
52
53
54
<?php
namespace Dash;
/**
* Gets a new array of the return values of `$iteratee` when called with successive elements in `$iterable`.
*
* Unlike `map()`, keys in `$iterable` are preserved.
*
* @see map(), mapResult()
*
* @param iterable|stdClass|null $iterable
* @param callable|string|integer $iteratee (optional) If a callable, invoked with `($value, $key, $iterable)`
* for each element in `$iterable`;
* if a string or integer, will use `Dash\property($iteratee)` as the iteratee
* @return array A new array with the same keys as `$iterable`
*
* @example
Dash\mapValues(['a' => 1, 'b' => 2, 'c' => 3], function ($value) {
return $value * 2;
});
// === ['a' => 2, 'b' => 4, 'c' => 6]
*
* @example With a path `$iteratee`
$data = [
'jdoe' => ['name' => ['first' => 'John', 'last' => 'Doe']],
'mjane' => ['name' => ['first' => 'Mary', 'last' => 'Jane']],
'psmith' => ['name' => ['first' => 'Pete', 'last' => 'Smith']],
];
Dash\mapValues($data, 'name.last');
// === ['jdoe' => 'Doe', 'mjane' => 'Jane', 'psmith' => 'Smith']
*/
function mapValues($iterable, $iteratee = 'Dash\identity')
{
assertType($iterable, ['iterable', 'stdClass', 'null'], __FUNCTION__);
if (is_null($iterable)) {
return [];
}
$mapped = [];
foreach ($iterable as $key => $value) {
if (hasDirect($value, $iteratee)) {
$mapped[$key] = getDirect($value, $iteratee);
}
else {
$mapper = is_callable($iteratee) ? $iteratee : property($iteratee, null);
$mapped[$key] = call_user_func($mapper, $value, $key, $iterable);
}
}
return $mapped;
}