Write a PHP program to memoize a given function results in memory
<?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) }
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
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