forked from lstrojny/functional-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoize.php
More file actions
52 lines (43 loc) · 1.44 KB
/
Memoize.php
File metadata and controls
52 lines (43 loc) · 1.44 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
<?php
/**
* @package Functional-php
* @author Lars Strojny <lstrojny@php.net>
* @copyright 2011-2021 Lars Strojny
* @license https://opensource.org/licenses/MIT MIT
* @link https://github.com/lstrojny/functional-php
*/
namespace Functional;
use const E_USER_DEPRECATED;
/**
* Memoizes callbacks and returns their value instead of calling them
*
* @param callable|null $callback Callable closure or function. Pass null to reset memory
* @param array $arguments Arguments
* @param array|string $key Optional memoize key to override the auto calculated hash
* @return mixed
* @no-named-arguments
*/
function memoize(?callable $callback = null, $arguments = [], $key = null)
{
static $storage = [];
if ($callback === null) {
$storage = [];
return null;
}
if (\is_callable($key)) {
\trigger_error('Passing a callable as key is deprecated and will be removed in 2.0', E_USER_DEPRECATED);
$key = $key();
} elseif (\is_callable($arguments)) {
\trigger_error('Passing a callable as key is deprecated and will be removed in 2.0', E_USER_DEPRECATED);
$key = $arguments();
}
if ($key === null) {
$key = value_to_key(\array_merge([$callback], $arguments));
} else {
$key = value_to_key($key);
}
if (!isset($storage[$key]) && !\array_key_exists($key, $storage)) {
$storage[$key] = $callback(...$arguments);
}
return $storage[$key];
}