Sha256: 21de1cccce2caa51525c79651c52948f8dcbcdad50e72b3154b24f9a16de66a1

Contents?: true

Size: 912 Bytes

Versions: 14

Compression:

Stored size: 912 Bytes

Contents

module Tins
  class LRUCache
    include Enumerable

    class << self
      private

      my_nil = Object.new.freeze

      define_method(:not_exist) do
        my_nil
      end
    end

    def initialize(capacity)
      @capacity = capacity
      @data     = {}
    end

    attr_reader :capacity

    def [](key)
      case value = @data.delete(key){ not_exist }
      when not_exist
        nil
      else
        @data[key] = value
      end
    end

    def []=(key, value)
      @data.delete(key)
      @data[key] = value
      if @data.size > @capacity
        @data.delete(@data.keys.first)
      end
      value
    end

    def each(&block)
      @data.reverse_each(&block)
    end

    def delete(key)
      @data.delete(key)
    end

    def clear
      @data.clear
    end

    def size
      @data.size
    end

    private

    def not_exist
      self.class.send(:not_exist)
    end
  end
end

Version data entries

14 entries across 14 versions & 2 rubygems

Version Path
tins-1.37.0 lib/tins/lru_cache.rb
tins-1.36.1 lib/tins/lru_cache.rb
tins-1.36.0 lib/tins/lru_cache.rb
tins-1.35.0 lib/tins/lru_cache.rb
tins-1.34.0 lib/tins/lru_cache.rb
tins-1.33.0 lib/tins/lru_cache.rb
tdiary-5.2.4 vendor/bundle/ruby/3.1.0/gems/tins-1.31.1/lib/tins/lru_cache.rb
tins-1.32.1 lib/tins/lru_cache.rb
tins-1.32.0 lib/tins/lru_cache.rb
tdiary-5.2.3 vendor/bundle/ruby/3.1.0/gems/tins-1.31.1/lib/tins/lru_cache.rb
tdiary-5.2.2 vendor/bundle/ruby/3.1.0/gems/tins-1.31.1/lib/tins/lru_cache.rb
tins-1.31.1 lib/tins/lru_cache.rb
tdiary-5.2.1 vendor/bundle/ruby/3.1.0/gems/tins-1.31.0/lib/tins/lru_cache.rb
tins-1.31.0 lib/tins/lru_cache.rb