Reduce, map and filter:
$set = new Set([1, 3, 5, 7]);
$sum = $set->reduce(function ($acc, $x) {
return $acc + $x;
});
echo $sum;
// output: 16
$set = new Set([0, 1, 2, 3]);
$squares = $set->map(function ($x) {
return $x * $x;
});
echo $squares;
// output: { 0, 1, 4, 9 }
$set = new Set([0, 1, 2, 3, 4, 5, 6, 7]);
$odd = $set->filter(function($x) {
return $x % 2 == 1;
});
echo $odd;
// output: { 1, 3, 5, 7 }
Collections implement ArrayAccess
, Iterator
and Countable
interfaces, so in many ways you can work with them like you work with standard PHP arrays:
$map[] = ['foo' => 'bar'];
$value = $map[0];
unset($map[0]);
count($map);
foreach ($map as $key => $value);
Mutations while iterating work as expected:
$set = new Set([ 1, 2, 3 ]);
$previous = false;
foreach ($set as $elem) {
if ($previous) $set->remove($previous);
$previous = $elem;
}
echo $set;
// output: { 3 }
map/filter/reduce are implemented as a trait that you can add to your own collections.
We read code that uses vanilla PHP array functions by starting from inner arguments and moving outward:
array_values(array_map(function ($cId) { return new ObjectId($cId); }, $cIds));
Cardinal Collections object-oriented approach with method chaining results in code that reads from left to right:
(new Set($cIds))->map(function ($cId) { return new ObjectId($cId); })->values();
Vanilla PHP array_map()
only maps array values:
$pidsToExitCodes = reapAnyChildren();
$jobIds = array_map(function ($pid) {
return handleTerminatedProcess($pid);
}, array_keys($pidsToExitCodes));
Cardinal Collections Map::map()
allows us to map keys and values, so we can easily refactor the above code in order to process additional information (in this example, exit codes) with no added code complexity:
$pidsToExitCodes = new Map(reapAnyChildren());
$pidsToJobIds = $pidsToExitCodes->map(function ($pid, $exitCode) {
return [$pid, handleTerminatedProcess($pid, $exitCode)];
});
Map(iterable $iterable = [])
Creates a new Map, initialized using keys and values from the given iterable. If called without arguments, an empty Map is created.
putIfAbsent($key, $value)
If the key is not in the Map, adds a new key/value pair, returning null. If the key is present in the Map, returns the existing value.
append($value): Map
Appends a value to the Map, using the next available numeric key. Returns the Map.
get($key, $default = null)
Returns the value associated with the key, or $default
value if the key is not present in the Map.
Set(iterable $iterable = [])
Creates a new Set, initialized using values of the given iterable. If called without arguments, an empty Set is created.
remove($element): Set
Removes an element from the Set, returning the Set without the element.
difference(Set $otherSet): Set
Returns a new Set with all members of Set that are not members of $otherSet
.