Arrays\filterMap()

higher-order transformer lazy accepts iterable returns Closure pure
(T → bool, T → U) → (Iterable → Iterable)
At a glance — Filter and map in one traversal — avoids a double iteration. Lazy — feeds a Generator through both steps element-by-element.

Create a function which filters and then maps an array. This is done by defining both the predicate and the mapping function.

/**
 * Creates a Closure which takes an array, applies a filter, then maps the
 * results of the map.
 *
 *
 * @param callable(mixed):bool $filter Function to of filter contents
 * @param callable(mixed):mixed $map Function to map results of filter function.
 * @return Closure(array<int|string, mixed>):array<int|string, mixed>
 */
Arrays\filterMap(callable $filter, callable $map): Closure

Returned Closure

When Arrays\filterMap() is called, it returns the following Closure which can be used like a regular function.

/**
 * @param array<int|string, mixed> $array The array to filter then map.
 * @return array<int|string, mixed>
 */
$function (array $data): array

Examples

Partial Application

This can be used to create a simple closure which can be used as a regular function.

// Create a function that will remove all none integer values and then multiply by 2.
$filterMap = Arrays\filterMap('is_int', fn($v) => $v * 2);

// Called as a function.  
var_dump($filterMap([1, 'Apple', 3.14, '4', 5, 10])); // [2, 10, 20] 

Curried

This can be called inline using currying.

// Filter out all none string values and then convert to uppercase.
var_dump(
 Arrays\filterMap('is_string', 'strtoupper')
 (['Apple', 1, 'Orange', 2, 'Banana', 3, 'Pear', 4, 'Peach', 5])
);  
// ['APPLE', 'ORANGE', 'BANANA', 'PEAR', 'PEACH']

Details

  • Group: Arrays
  • Subgroup: Array filter
  • Core Functions: array_filter(), array_map()
  • Since: 0.1.0
  • Source: