Skip to content

Instantly share code, notes, and snippets.

@danilopinotti
Last active March 10, 2022 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danilopinotti/84f17dfbb6a85b5ae2b50a8a8082d76b to your computer and use it in GitHub Desktop.
Save danilopinotti/84f17dfbb6a85b5ae2b50a8a8082d76b to your computer and use it in GitHub Desktop.
PHP Memoization inspired by @CViniciusSDias
<?php
use Ds\Map;
function memo(callable $function): callable
{
$cache = new Map();
return function (mixed ...$args) use (&$cache, $function): mixed {
if (isset($cache[$args])) {
return $cache[$args];
}
$result = $function(...$args);
return $cache[$args] = $result;
};
}
function sum(int $a, int $b): int
{
echo 'Executing sum.'.PHP_EOL;
return $a + $b;
}
$sum = memo(fn(...$args) => sum(...$args));
echo $sum(1, 2).PHP_EOL;
echo $sum(1, 3).PHP_EOL;
echo $sum(1, 2).PHP_EOL; // Should use cache
echo $sum(1, 3).PHP_EOL; // Should use cache
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment