<?php
function memoize(callable $fn): callable {
$cache = [];
return function (...$args) use ($fn, &$cache) {
$key = md5(serialize($args));
if (!array_key_exists($key, $cache)) {
$cache[$key] = $fn(...$args);
}
return $cache[$key];
};
}
$slowSqrt = memoize(function (int $n) {
sleep(1); // imagine an expensive computation
return sqrt($n);
});
echo $slowSqrt(9); // 3 — first call takes 1 second
echo $slowSqrt(9); // 3 — instant on subsequent calls
echo $slowSqrt(16); // 4 — first call for this arg
Create a free account and build your private vault. Share publicly whenever you want.