Skip to content

Instantly share code, notes, and snippets.

@mikemix
Last active August 21, 2022 11:06
Show Gist options
  • Save mikemix/c24a52dda95f6c4b47aa9efa767cceb4 to your computer and use it in GitHub Desktop.
Save mikemix/c24a52dda95f6c4b47aa9efa767cceb4 to your computer and use it in GitHub Desktop.

Revisions

  1. mikemix revised this gist Aug 14, 2022. 1 changed file with 3 additions and 3 deletions.
    6 changes: 3 additions & 3 deletions lru-impl.php
    Original 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) {
    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)]);
    \reset($this->items);
    unset($this->items[\key($this->items)]);
    }

    /** {@inheritDoc} */
  2. mikemix created this gist Aug 13, 2022.
    72 changes: 72 additions & 0 deletions lru-impl.php
    Original 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;
    }
    }