class LruQache

require “lru_qache/lru_queue”

Constants

DEFAULT_VAL
INVALID_CAPACITY
InvalidCapacityError
MAX_CAPACITY

Attributes

cache[R]
capacity[R]
options[R]

Public Class Methods

new(capacity = MAX_CAPACITY, options = { default_val: DEFAULT_VAL }) click to toggle source

@param capacity [Integer] Takes a number as an input and @param options [Hash] optional hash for some settings like custom value if \ key is not present @option options [Integer] :default_val

# File lib/lru_qache.rb, line 15
def initialize(capacity = MAX_CAPACITY, options = { default_val: DEFAULT_VAL })
  raise InvalidLimitError, INVALID_CAPACITY unless capacity.is_a?(Integer)
  @cache = {}
  @options = options
  @capacity = capacity
end

Public Instance Methods

[](key)
Alias for: get
[]=(key, val)
Alias for: set
get(key) click to toggle source

This gets the value based on the key is provided, updates the key usage

@param key input parameter @return value [Object] if key is present @example get(x)

# File lib/lru_qache.rb, line 27
def get(key)
  value = retrieve(key)
  update_lru(key) unless value == options[:default_val]
  value
end
Also aliased as: []
set(key, val) click to toggle source

Sets the value of cache's key

@param key any valid object @param key any valid object @example set('a', 1) @todo Add validation to the key e.g. only Symbol, String or Integer etc.

# File lib/lru_qache.rb, line 39
def set(key, val)
  @cache.delete(key) if cache.has_key?(key)
  @cache[key] = val
  remove_lru_if_needed
  val
end
Also aliased as: []=

Private Instance Methods

remove_lru_if_needed() click to toggle source

This removes the least recently used key from cache and also updates queue

@param key input parameter

# File lib/lru_qache.rb, line 61
def remove_lru_if_needed
  # update the queue with new key
  # remove LRU key if capacity is full.
  cache.shift if cache.size > capacity
end
retrieve(key) click to toggle source

This is used for not modifying the 'last_used' key when using internal logic

@param key input parameter @return value [Object] if key is present

# File lib/lru_qache.rb, line 54
def retrieve(key)
  cache.fetch(key) { options[:default_val] }
end
update_lru(key) click to toggle source

Updates the lru with the key, removes key and sets again so key goes to the last

@param Takes key the input, it can be any valid Object needed for hash

# File lib/lru_qache.rb, line 71
def update_lru(key)
  val = cache.delete(key)
  cache[key] = val
end