HH\Set::map

Returns a Set containing the values after an operation has been applied to each value in the current Set.

Description

public function map(
  callable $callback,
): Set<Tu>

Returns a Set containing the values after an operation has been applied to each value in the current Set.

Every value in the current Set is affected by a call to map(), unlike filter() where only values that meet a certain criteria are affected.

Parameters

  • callable $callback - The callback containing the operation to apply to the current Set values.

Return Values

  • Set<Tu> - a Set containing the values after a user-specified operation is applied.

Examples

In this example the Set's elements are mapped to the same type (strings):

<?hh

namespace Hack\UserDocumentation\API\Examples\Set\Map\Strings;

$s  = Set {'red', 'green', 'blue', 'yellow'};

$capitalized = $s->map(fun('strtoupper'));
var_dump($capitalized);

$shortened = $s->map($color ==> substr($color, 0, 3));
var_dump($shortened);
Output
object(HH\Set)#2 (4) {
  string(3) "RED"
  string(5) "GREEN"
  string(4) "BLUE"
  string(6) "YELLOW"
}
object(HH\Set)#4 (4) {
  string(3) "red"
  string(3) "gre"
  string(3) "blu"
  string(3) "yel"
}

In this example the Set's elements are mapped to a different type (ints):

<?hh

namespace Hack\UserDocumentation\API\Examples\Set\Map\Ints;

$s  = Set {'red', 'green', 'blue', 'yellow'};

$lengths = $s->map(fun('strlen'));
var_dump($lengths);
Output
object(HH\Set)#2 (4) {
  int(3)
  int(5)
  int(4)
  int(6)
}