Class: LruQache

Inherits:
Object
  • Object
show all
Defined in:
lib/lru_qache.rb

Overview

require “lru_qache/lru_queue”

Constant Summary collapse

MAX_CAPACITY =

LRU cache is caching technique based on recently used data.

5
DEFAULT_VAL =
-1
InvalidCapacityError =
Class.new RuntimeError
INVALID_CAPACITY =
'Capacity must be valid number'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(capacity = MAX_CAPACITY, options = { default_val: DEFAULT_VAL }) ⇒ LruQache

key is not present

Parameters:

  • capacity (Integer) (defaults to: MAX_CAPACITY)

    Takes a number as an input and

  • options (Hash) (defaults to: { default_val: DEFAULT_VAL })

    optional hash for some settings like custom value if \

Options Hash (options):

  • :default_val (Integer)

Raises:

  • (InvalidLimitError)


15
16
17
18
19
20
# 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

Instance Attribute Details

#cacheObject (readonly)

Returns the value of attribute cache.



9
10
11
# File 'lib/lru_qache.rb', line 9

def cache
  @cache
end

#capacityObject (readonly)

Returns the value of attribute capacity.



9
10
11
# File 'lib/lru_qache.rb', line 9

def capacity
  @capacity
end

#optionsObject (readonly)

Returns the value of attribute options.



9
10
11
# File 'lib/lru_qache.rb', line 9

def options
  @options
end

Instance Method Details

#get(key) ⇒ Object Also known as: []

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

Examples:

get(x)

Parameters:

  • key

    input parameter



27
28
29
30
31
# File 'lib/lru_qache.rb', line 27

def get(key)
  value = retrieve(key)
  update_lru(key) unless value == options[:default_val]
  value
end

#set(key, val) ⇒ Object Also known as: []=

TODO:

Add validation to the key e.g. only Symbol, String or Integer etc.

Sets the value of cache’s key

Examples:

set(‘a’, 1)

Parameters:

  • key

    any valid object

  • key

    any valid object



39
40
41
42
43
44
# 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