class HashMap
Attributes
count[R]
Public Class Methods
new(num_buckets = 8)
click to toggle source
# File lib/simms_structures/hash_map.rb, line 10 def initialize(num_buckets = 8) @store = Array.new(num_buckets) { LinkedList.new } @count = 0 end
Public Instance Methods
bucket(key)
click to toggle source
# File lib/simms_structures/hash_map.rb, line 69 def bucket(key) @store[key.hash % num_buckets] end
delete(key)
click to toggle source
# File lib/simms_structures/hash_map.rb, line 29 def delete(key) @count-= 1 if bucket(key).remove(key) end
each(&block)
click to toggle source
# File lib/simms_structures/hash_map.rb, line 33 def each(&block) @store.each do |bucket| bucket.each do |link| block.yield(link.key, link.val) end end end
get(key)
click to toggle source
# File lib/simms_structures/hash_map.rb, line 25 def get(key) bucket(key).get(key) end
Also aliased as: []
include?(key)
click to toggle source
# File lib/simms_structures/hash_map.rb, line 15 def include?(key) bucket(key).include?(key) end
num_buckets()
click to toggle source
private
# File lib/simms_structures/hash_map.rb, line 53 def num_buckets @store.length end
resize!()
click to toggle source
# File lib/simms_structures/hash_map.rb, line 57 def resize! old_store = @store @store = Array.new( num_buckets * 2 ) { LinkedList.new } @count = 0 old_store.each do |bucket| bucket.each do |link| self[link.key] = link.val end end end
set(key, val)
click to toggle source
# File lib/simms_structures/hash_map.rb, line 19 def set(key, val) resize! if @count == num_buckets include?(key) ? delete(key) : (@count += 1) bucket(key).insert(key, val) end
Also aliased as: []=
to_s()
click to toggle source
# File lib/simms_structures/hash_map.rb, line 41 def to_s pairs = inject([]) do |strs, (k, v)| strs << "#{k.to_s} => #{v.to_s}" end "{\n" + pairs.join(",\n") + "\n}" end