Q:

Write a PHP program to memoize a given function results in memory

0

Write a PHP program to memoize a given function results in memory

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

<?php
//Licence: https://bit.ly/2CFA5XY
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];
    };
}

$memoizedAdd = memoize(
    function ($num) {
        return $num + 10;
    }
);

var_dump($memoizedAdd(5));  
var_dump($memoizedAdd(6));  
var_dump($memoizedAdd(5));  
?>

Sample Output:

array(2) {
  ["result"]=>
  int(15)
  ["cached"]=>
  bool(false)
}
array(2) {
  ["result"]=>
  int(16)
  ["cached"]=>
  bool(false)
}
array(2) {
  ["result"]=>
  int(15)
  ["cached"]=>
  bool(true)
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now