/** * Returns sequence items that satisfy the predicate * * @param callable $predicate * @param array|\Traversable $sequence * @return array */ function filter(callable $predicate, $sequence) { args\expects(args\traversable, $sequence); $sequence = ds\traversableToArray($sequence); $filtered = array_filter($sequence, $predicate); return ds\isList($sequence) ? array_values($filtered) : $filtered; }
/** * Returns a random element from a non-empty sequence * * @param array|\Traversable $sequence * @return mixed */ function choice($sequence) { if (!$sequence) { throw new \InvalidArgumentException('Sequence is empty'); } args\expects(args\traversable, $sequence); $sequence = ds\traversableToArray($sequence); return $sequence[array_rand($sequence)]; }
public function testTraversableToArray() { $this->assertEquals([1, 2, 3], traversableToArray([1, 2, 3])); $this->assertEquals([1, 2, 3], traversableToArray(new ArrayObject(1, 2, 3))); $this->assertEquals([1, 2, 3], traversableToArray(new \ArrayObject([1, 2, 3]))); $range = function ($min, $max) { for ($i = $min; $i <= $max; ++$i) { (yield $i); } }; $this->assertEquals([1, 2, 3], traversableToArray($range(1, 3))); }
/** * Returns array which contains sequence items sorted by keys * * @param array|\Traversable $array * @param bool $reversed * @return array */ function keySorted($array, $reversed = false) { args\expects(args\traversable, $array); args\expects(args\bool, $reversed); $array = ds\traversableToArray($array); if ($reversed) { krsort($array); } else { ksort($array); } return $array; }