Skip to content

Instantly share code, notes, and snippets.

@SebSept
Created August 25, 2021 14:40
Show Gist options
  • Save SebSept/a0ff03592f0b386be58b8615ce066902 to your computer and use it in GitHub Desktop.
Save SebSept/a0ff03592f0b386be58b8615ce066902 to your computer and use it in GitHub Desktop.
<?php
function memoize(Closure $fn) : Closure {
return function (...$args) use ($fn) {
static $results = [];
$argsHash = sha1( join("", array_map('serialize', func_get_args())));
$results[$argsHash] = $results[$argsHash] ?? $fn(...$args);
return $results[$argsHash];
};
}
// the original fn
$square = function (int $toSquare) { sleep(1); return $toSquare**2; };
// the memoized version
$memoizedSquare = memoize($square);
//echo $square(2).PHP_EOL;
//echo $square(4).PHP_EOL;
echo $memoizedSquare(2).PHP_EOL; // not set
echo $memoizedSquare(2).PHP_EOL; // set
echo $memoizedSquare(4).PHP_EOL; // not set
echo $memoizedSquare(2).PHP_EOL; // set
echo $memoizedSquare(4).PHP_EOL; // set
echo $memoizedSquare(5).PHP_EOL; // not set
$add = fn($a, $b) => $a + $b;
$memoizedAdd = memoize($add);
echo $memoizedAdd(3, 5).PHP_EOL;
echo $memoizedAdd(5, 5).PHP_EOL;
echo $memoizedAdd(5, 5).PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment