Last active
August 21, 2022 11:06
-
-
Save mikemix/c24a52dda95f6c4b47aa9efa767cceb4 to your computer and use it in GitHub Desktop.
Revisions
-
mikemix revised this gist
Aug 14, 2022 . 1 changed file with 3 additions and 3 deletions.There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -39,14 +39,14 @@ public function add(string $key, $item): void $this->items[$key] = $item; // there's still room for new items if (\count($this->items) <= $this->size) { return; } // no room for new items // remove the least used element \reset($this->items); unset($this->items[\key($this->items)]); } /** {@inheritDoc} */ -
mikemix created this gist
Aug 13, 2022 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,72 @@ <?php declare(strict_types=1); namespace App\Cache; /** * @template TCacheItem * @template-implements LRUCacheInterface<TCacheItem> */ final class LRUCache implements LRUCacheInterface { /** * @var array<string, TCacheItem> */ private array $items = []; private int $size; public function __construct(int $size) { if ($size <= 0) { throw new InvalidArgumentException('Cache size must be greater than 0'); } $this->size = $size; } /** {@inheritDoc} */ public function add(string $key, $item): void { // already on the list if (isset($this->items[$key])) { $this->items[$key] = $item; $this->moveToFront($key); return; } $this->items[$key] = $item; // there's still room for new items if (count($this->items) <= $this->size) { return; } // no room for new items // remove the least used element reset($this->items); unset($this->items[key($this->items)]); } /** {@inheritDoc} */ public function get(string $key) { if (false === isset($this->items[$key])) { return null; } $this->moveToFront($key); return $this->items[$key]; } private function moveToFront(string $key): void { $cachedItem = $this->items[$key]; unset($this->items[$key]); $this->items[$key] = $cachedItem; } }