Last active
December 9, 2020 13:13
-
-
Save ngoylufo/3c1e9257dfeec3c152dba1d1e1de2fdb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Label | |
{ | |
private $label; | |
public function __construct(string $label) | |
{ | |
$this->label = $label; | |
} | |
public function getText(): string | |
{ | |
return $this->label; | |
} | |
} | |
function pluralizeLabel(Label $label): string | |
{ | |
$entries = [ | |
'angle' => ['singular' => 'angle', 'plural' => 'angles'], | |
'issue' => ['singular' => 'issue', 'plural' => 'issues'] | |
]; | |
echo "Reading from database. \n"; | |
$text = strtolower($label->getText()); | |
return $entries[$text]['plural']; | |
} | |
function memoize(callable $fn, callable $serialize = null): callable | |
{ | |
$serialize = $serialize ?: 'serialize'; | |
return function (...$args) use ($fn, $serialize) { | |
static $cache = []; | |
$key = $serialize($args); | |
return $cache[$key] ?? ($cache[$key] = $fn(...$args)); | |
}; | |
} | |
// Example | |
$issue = new Label('Issue'); | |
// use the closure instead of serialize to get the key. | |
$pluralize = memoize('pluralizeLabel', function(array $args) { | |
$label = $args[0]; | |
return $label->getText(); | |
}); | |
// connects to the database, finds record, returns plural. | |
echo "First call: \n"; | |
echo $pluralize($issue) . "\n\n"; // => issues | |
// Gets the value from the cache instead | |
echo "Second call: \n"; | |
echo $pluralize($issue) . "\n\n"; // => issues | |
// Gets the value from the cache instead | |
echo "Third call: \n"; | |
echo $pluralize($issue) . "\n\n"; // => issues |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment