-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctional.php
More file actions
76 lines (66 loc) · 2.05 KB
/
Functional.php
File metadata and controls
76 lines (66 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
namespace x3\Functional;
use x3\Functional\ArgPlaceholder as _;
class Functional
{
/**
* Return the method with reversed argument order
*
* @param callback $method The method to reverse
*
* @return closure The reversed method
*/
public static function reverseArgs($method)
{
return function () use ($method) {
return call_user_func_array($method, array_reverse(func_get_args()));
};
}
/**
* Curry `$callback` with the passed arguments
*
* @param callable $callback The callback to curry
* @param mixed $arg ... The arguments to add by default
*
* @return closure The curried function
*/
public static function curry($callback)
{
$curryArgs = array_slice(func_get_args(), 1);
$argsCallback = function ($args, $arg) {
$placeHolderIndex = array_search((string)new _, $args);
if ($placeHolderIndex !== false) {
$args[$placeHolderIndex] = $arg;
} else {
$args[] = $arg;
}
return $args;
};
return function () use ($callback, $curryArgs, $argsCallback) {
$args = array_reduce(func_get_args(), $argsCallback, $curryArgs);
return call_user_func_array($callback, $args);
};
}
public static function compose()
{
$callables = array_reverse(func_get_args());
$callback = function ($arg, $callable) {
return call_user_func($callable, $arg);
};
return function ($parameter) use ($callables, $callback) {
return array_reduce($callables, $callback, $parameter);
};
}
public static function memoize($callable)
{
$store = [];
return function () use ($callable, &$store) {
$args = func_get_args();
$key = json_encode($args);
if (!isset($store[$key])) {
$store[$key] = call_user_func_array($callable, $args);
}
return $store[$key];
};
}
}