Last active
March 10, 2022 17:22
-
-
Save danilopinotti/84f17dfbb6a85b5ae2b50a8a8082d76b to your computer and use it in GitHub Desktop.
PHP Memoization inspired by @CViniciusSDias
This file contains 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
<?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