Example #1
0
/**
 * 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;
}
Example #2
0
/**
 * 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)];
}
Example #3
0
 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)));
 }
Example #4
0
/**
 * 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;
}