Example #1
0
/**
 * f\compose(callable $fn1 [, $fn...])
 *
 * Returns a function that is the composition of the passed functions.
 * The first function (right to left) receives the passed args, and the rest the result
 * of the previous function.
 *
 * $revUp = f\compose('strtoupper', 'strrev');
 * $revUp('hello');
 * => OLLEH
 */
function compose()
{
    $fns = func_get_args();
    $compose = function ($composition, $fn) {
        return function () use($composition, $fn) {
            return call_user_func($fn, call_user_func_array($composition, func_get_args()));
        };
    };
    return f\reduce($compose, f\reverse($fns));
}
Example #2
0
 /**
  * @dataProvider provideReduceOneItem
  */
 public function testOneItemCollectionWithInitialValue($coll)
 {
     $calls = array();
     $result = f\reduce(function ($result, $value) use(&$calls) {
         $calls[] = func_get_args();
         return $result + $value;
     }, $coll, 6);
     $this->assertSame(8, $result);
     $expected = array(array(6, 2));
     $this->assertSame($expected, $calls);
 }
Example #3
0
function benchmark_compares()
{
    $number = 100;
    $array = range(1, $number);
    return ['map' => ['array_map' => function () use($array) {
        array_map(function () {
        }, $array);
    }, 'f/map' => function () use($array) {
        f\map(function () {
        }, $array);
    }], 'reduce' => ['array_reduce' => function () use($array) {
        array_reduce($array, function ($a, $b) {
            return $a + $b;
        });
    }, 'f/reduce' => function () use($array) {
        f\reduce(function ($a, $b) {
            return $a + $b;
        }, $array);
    }], 'filter' => ['array_filter' => function () use($array) {
        array_filter($array, function ($v) {
            return $v % 2;
        });
    }, 'f/filter' => function () use($array) {
        f\filter(function ($v) {
            return $v % 2;
        }, $array);
    }], 'rename_keys' => ['raw' => function () use($array) {
        $result = array();
        foreach ($array as $key => $v) {
            $result['a' . $key] = $v;
        }
    }, 'f\\rename_keys' => function () use($array) {
        f\rename_keys($array, f\map(function ($k) {
            return 'a' . $k;
        }, $array));
    }]];
}