Skip to content

Instantly share code, notes, and snippets.

@denis-mironov
Last active January 18, 2024 16:49
Show Gist options
  • Save denis-mironov/403290369380e81991c4e2faa3f34476 to your computer and use it in GitHub Desktop.
Save denis-mironov/403290369380e81991c4e2faa3f34476 to your computer and use it in GitHub Desktop.
Simple in memory cache implementation (ruby class)
# An in memory cache implementation that expires the least recently used items, and limits cache size by a maximum number of items.

class Cache
  attr_reader :store, :max_size

  def initialize(max_size)
    @max_size = max_size
    @store = {}
  end

  def write(key, value)
    remove_least_recently_used_key if count == max_size

    store[key] = { value: value, counter: 0 }
  end

  def read(key)
    store[key][:counter] += 1

    store[key][:value]
  end

  def delete(key)
    store.delete(key)
  end

  def clear
    store.clear
  end

  def count
    store.size
  end

  private

  def remove_least_recently_used_key
    key = store.min_by { |k, v| v[:counter] }.first
    store.delete(key)
  end
end

cache = Cache.new(3)

cache.write('key', 'value')
cache.write('key_1', 'value_1')
cache.write('key_2', 'value_2')
p cache.store

# permorm operations on cache keys
p cache.read('key')
p cache.read('key')
p cache.read('key_1')
p cache.read('key_1')
p cache.read('key_2')
p cache.store

# key with value_2 will be removed before writing current key
cache.write('key_3', 'value_3')
p cache.store
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment