forked from isisAnchalee/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash-map.rb
69 lines (53 loc) · 1.13 KB
/
hash-map.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class HashMap
include Enumerable
attr_reader :count
def initialize(num_buckets = 8)
@store = Array.new(num_buckets) { LinkedList.new }
@count = 0
end
def include?(key)
bucket(key).include?(key)
end
def set(key, val)
delete(key) if include?(key)
resize! if @count >= num_buckets
@count += 1
bucket(key).insert(key, val)
end
def get(key)
bucket(key).get(key)
end
def delete(key)
removal = bucket(key).remove(key)
@count -= 1 if removal
removal
end
def each
@store.each do |bucket|
bucket.each { |link| yield [link.key, link.val] }
end
end
def to_s
pairs = inject([]) do |strs, (k, v)|
strs << "#{k.to_s} => #{v.to_s}"
end
"{\n" + pairs.join(",\n") + "\n}"
end
alias_method :[], :get
alias_method :[]=, :set
private
def num_buckets
@store.length
end
def resize!
old_store = @store
@store = Array.new(num_buckets * 2) { LinkedList.new }
@count = 0
old_store.each do |bucket|
bucket.each { |link| set(link.key, link.val) }
end
end
def bucket(key)
@store[key.hash % num_buckets]
end
end