Skip to content

Commit d629c50

Browse files
committed
wip: underscore function related utils
1 parent 110a13a commit d629c50

File tree

1 file changed

+49
-1
lines changed

1 file changed

+49
-1
lines changed

src/Underscore.php

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,54 @@
22

33
namespace Ahc\Underscore;
44

5-
final class Underscore extends UnderscoreCollection
5+
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+
12+
public function memoize(callable $fn)
13+
{
14+
static $memo = [];
15+
16+
$hash = \md5(\json_encode(\array_slice(\func_get_args(), 1)));
17+
18+
if (isset($memo[$hash])) {
19+
return $memo[$hash];
20+
}
21+
22+
return $memo[$hash] = \call_user_func_array($fn, $args);
23+
}
24+
25+
public function delay(callable $fn, $wait)
26+
{
27+
usleep(1000 * $wait);
28+
29+
return \call_user_func_array($fn, \array_slice(\func_get_args(), 2));
30+
}
31+
32+
public function throttle($fn, $wait)
33+
{
34+
$previous = 0;
35+
$result = null;
36+
37+
return function () use ($fn, &$previous, &$result, &$wait) {
38+
$now = $this->now();
39+
$args = \func_get_args();
40+
41+
if (!$previous) {
42+
$previous = $now;
43+
}
44+
45+
$remaining = $wait - ($now - $previous);
46+
47+
if ($remaining <= 0 || $remaining > $wait) {
48+
$previous = $now;
49+
$result = \call_user_func_array($fn, $args);
50+
}
51+
52+
return $result;
53+
};
54+
}
755
}

0 commit comments

Comments
 (0)