Skip to content

Commit 85a2002

Browse files
committed
fix: memoize() and delay(), remove bind(), cleanup throttle()
1 parent d629c50 commit 85a2002

File tree

1 file changed

+41
-18
lines changed

1 file changed

+41
-18
lines changed

src/Underscore.php

Lines changed: 41 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,39 +4,62 @@
44

55
final class Underscore extends UnderscoreArray
66
{
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+
*/
1215
public function memoize(callable $fn)
1316
{
1417
static $memo = [];
1518

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()));
1721

18-
if (isset($memo[$hash])) {
19-
return $memo[$hash];
20-
}
22+
if (isset($memo[$hash])) {
23+
return $memo[$hash];
24+
}
2125

22-
return $memo[$hash] = \call_user_func_array($fn, $args);
26+
return $memo[$hash] = \call_user_func_array($fn, $args);
27+
};
2328
}
2429

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+
*/
2538
public function delay(callable $fn, $wait)
2639
{
27-
usleep(1000 * $wait);
40+
return function () use ($fn, $wait) {
41+
\usleep(1000 * $wait);
2842

29-
return \call_user_func_array($fn, \array_slice(\func_get_args(), 2));
43+
return \call_user_func_array($fn, \func_get_args());
44+
};
3045
}
3146

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)
3357
{
34-
$previous = 0;
35-
$result = null;
58+
static $previous = 0;
59+
static $result = null;
3660

3761
return function () use ($fn, &$previous, &$result, &$wait) {
38-
$now = $this->now();
39-
$args = \func_get_args();
62+
$now = $this->now();
4063

4164
if (!$previous) {
4265
$previous = $now;
@@ -46,7 +69,7 @@ public function throttle($fn, $wait)
4669

4770
if ($remaining <= 0 || $remaining > $wait) {
4871
$previous = $now;
49-
$result = \call_user_func_array($fn, $args);
72+
$result = \call_user_func_array($fn, \func_get_args());
5073
}
5174

5275
return $result;

0 commit comments

Comments
 (0)