Class: DataStructures101::Hash::Bucket

Inherits:
Object
  • Object
show all
Defined in:
lib/data_structures_101/hash/bucket.rb

Overview

Utility class to manipulate (key, pairs) that have same hash code.

See Also:

Author:

  • Rene Hernandez

Since:

  • 0.2

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBucket

Returns a new instance of Bucket.

Since:

  • 0.2



12
13
14
# File 'lib/data_structures_101/hash/bucket.rb', line 12

def initialize
  @table = []
end

Instance Attribute Details

#tableObject (readonly)

Since:

  • 0.2



10
11
12
# File 'lib/data_structures_101/hash/bucket.rb', line 10

def table
  @table
end

Instance Method Details

#[](key) ⇒ Object

Since:

  • 0.2



16
17
18
# File 'lib/data_structures_101/hash/bucket.rb', line 16

def [](key)
  find(key)
end

#[]=(key, value) ⇒ Object

Since:

  • 0.2



20
21
22
# File 'lib/data_structures_101/hash/bucket.rb', line 20

def []=(key, value)
  insert(key, value)
end

#delete(key) ⇒ Object

Since:

  • 0.2



45
46
47
48
49
50
51
52
53
# File 'lib/data_structures_101/hash/bucket.rb', line 45

def delete(key)
  idx = @table.find_index { |table_key, _| table_key == key }
  return nil if idx.nil?

  value = @table[idx].last
  @table[idx] = @table.last if idx != @table.size - 1
  @table.pop
  value
end

#eachObject

Since:

  • 0.2



55
56
57
58
59
60
61
# File 'lib/data_structures_101/hash/bucket.rb', line 55

def each
  return enum_for(:each) unless block_given?

  @table.each do |key, value|
    yield(key, value)
  end
end

#find(key) ⇒ Object

Since:

  • 0.2



40
41
42
43
# File 'lib/data_structures_101/hash/bucket.rb', line 40

def find(key)
  pair = @table.find { |table_key, _| table_key == key }
  pair.nil? ? nil : pair.last
end

#insert(key, value) ⇒ Object

Since:

  • 0.2



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/data_structures_101/hash/bucket.rb', line 24

def insert(key, value)
  idx = @table.find_index { |table_key, _| table_key == key }

  if idx.nil?
    @table << [key, value]
    return nil
  else
    value, @table[idx][1] = @table[idx][1], value
    return value
  end
end

#sizeObject

Since:

  • 0.2



36
37
38
# File 'lib/data_structures_101/hash/bucket.rb', line 36

def size
  @table.size
end