Skip to content

Commit

Permalink
Merge pull request #51 from jorgeavilacardenosa/memoize-reset-cache
Browse files Browse the repository at this point in the history
memoize reset cache
  • Loading branch information
jorgeavilacardenosa committed Mar 23, 2016
2 parents 22d5120 + 59b7194 commit eb8c183
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 5 deletions.
2 changes: 1 addition & 1 deletion docs/functions/memoize.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Returns the result of function evaluation for a set of parameters, and then on f

<dl>
<dt>fn</dt>
<dd>Function to be executed.</dd>
<dd>Function to be executed. Pass null to reset cache</dd>

<dt>args</dt>
<dd>Arguments to be passed to the called function.</dd>
Expand Down
18 changes: 14 additions & 4 deletions src/memoize.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,29 @@

namespace Akamon\Phunctional;

use Closure;

/**
* @since 0.1
*
* @param callable $fn function to be executed
* @param array $args arguments to be passed to the called function
* @param callable|null $fn function to be executed. Pass null to reset cache
* @param array $args arguments to be passed to the called function
*
* @return mixed
*/
function memoize(callable $fn, ...$args)
function memoize(callable $fn = null, ...$args)
{
static $cache = [];

$key = md5(spl_object_hash($fn) . serialize($args));
if (null === $fn) {
$cache = [];

return null;
}

$closureClass = Closure::class;
$keyFn = $fn instanceof $closureClass ? spl_object_hash($fn) : get_class($fn);
$key = md5($keyFn . serialize($args));

return $cache[$key] = array_key_exists($key, $cache) ? $cache[$key] : $fn(...$args);
}
10 changes: 10 additions & 0 deletions tests/MemoizeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,16 @@ public function it_should_call_return_the_value_of_the_called_function_caching_t
$this->assertSame($previousValue, memoize($this->functionWithRandReturn(), 1, 1000000));
}

/** @test */
public function it_should_reset_the_cache_if_function_to_be_executed_is_null()
{
$previousValue = memoize($this->functionWithRandReturn(), 1, 1000000);

memoize();

$this->assertNotSame($previousValue, memoize($this->functionWithRandReturn(), 1, 1000000));
}

/**
* @test
* @dataProvider fibonacciValues
Expand Down

0 comments on commit eb8c183

Please sign in to comment.