Created
October 23, 2023 23:47
-
-
Save joparara/50a4f6d0d2e723e466694c6d8795657e to your computer and use it in GitHub Desktop.
memoize
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
$memoizedAdd = memoize( | |
function ($num) { | |
return $num + 10; | |
} | |
); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
function memoize($func) | |
{ | |
return function () use ($func) { | |
static $cache = []; | |
$args = func_get_args(); | |
$key = serialize($args); | |
$cached = true; | |
if (!isset($cache[$key])) { | |
$cache[$key] = $func(...$args); | |
$cached = false; | |
} | |
return ['result' => $cache[$key], 'cached' => $cached]; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment