4
4
5
5
final class Underscore extends UnderscoreArray
6
6
{
7
- public function bind (\Closure $ fn , $ ctx )
8
- {
9
- \Closure::bind ($ fn , \is_object ($ ctx ) ? $ ctx : null );
10
- }
11
-
7
+ /**
8
+ * Returns a callable which when invoked caches the result for given arguments
9
+ * and reuses that result in subsequent calls.
10
+ *
11
+ * @param callable $fn The main callback.
12
+ *
13
+ * @return mixed
14
+ */
12
15
public function memoize (callable $ fn )
13
16
{
14
17
static $ memo = [];
15
18
16
- $ hash = \md5 (\json_encode (\array_slice (\func_get_args (), 1 )));
19
+ return function () use (&$ memo , $ fn ) {
20
+ $ hash = \md5 (\json_encode ($ args = \func_get_args ()));
17
21
18
- if (isset ($ memo [$ hash ])) {
19
- return $ memo [$ hash ];
20
- }
22
+ if (isset ($ memo [$ hash ])) {
23
+ return $ memo [$ hash ];
24
+ }
21
25
22
- return $ memo [$ hash ] = \call_user_func_array ($ fn , $ args );
26
+ return $ memo [$ hash ] = \call_user_func_array ($ fn , $ args );
27
+ };
23
28
}
24
29
30
+ /**
31
+ * Cache the result of callback for given arguments and reuse that in subsequent call.
32
+ *
33
+ * @param callable $fn The main callback.
34
+ * @param int $wait The time to wait in millisec.
35
+ *
36
+ * @return mixed
37
+ */
25
38
public function delay (callable $ fn , $ wait )
26
39
{
27
- usleep (1000 * $ wait );
40
+ return function () use ($ fn , $ wait ) {
41
+ \usleep (1000 * $ wait );
28
42
29
- return \call_user_func_array ($ fn , \array_slice (\func_get_args (), 2 ));
43
+ return \call_user_func_array ($ fn , \func_get_args ());
44
+ };
30
45
}
31
46
32
- public function throttle ($ fn , $ wait )
47
+ /**
48
+ * Returns a callable that wraps given callable which can be only invoked
49
+ * at most once per given $wait threshold.
50
+ *
51
+ * @param callable $fn The main callback.
52
+ * @param int $wait The callback will only be triggered at most once within this period.
53
+ *
54
+ * @return mixed The return set of callback if runnable else the previous cache.
55
+ */
56
+ public function throttle (callable $ fn , $ wait )
33
57
{
34
- $ previous = 0 ;
35
- $ result = null ;
58
+ static $ previous = 0 ;
59
+ static $ result = null ;
36
60
37
61
return function () use ($ fn , &$ previous , &$ result , &$ wait ) {
38
- $ now = $ this ->now ();
39
- $ args = \func_get_args ();
62
+ $ now = $ this ->now ();
40
63
41
64
if (!$ previous ) {
42
65
$ previous = $ now ;
@@ -46,7 +69,7 @@ public function throttle($fn, $wait)
46
69
47
70
if ($ remaining <= 0 || $ remaining > $ wait ) {
48
71
$ previous = $ now ;
49
- $ result = \call_user_func_array ($ fn , $ args );
72
+ $ result = \call_user_func_array ($ fn , \func_get_args () );
50
73
}
51
74
52
75
return $ result ;
0 commit comments