-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash_map.rb
74 lines (58 loc) · 1.22 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
70
71
72
73
74
require_relative '../linked_list/linked_list'
class HashMap
include Enumerable
attr_reader :count
def initialize(num_buckets = 8)
@store = Array.new(num_buckets) { DoublyLinkedList.new }
@count = 0
end
def include?(key)
bucket(key).include?(key)
end
def set(key, val)
resize! if @count >= num_buckets
if include?(key)
bucket(key).update(key, val)
else
bucket(key).append(key, val)
@count += 1
end
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} => #{v}"
end
"{\n" + pairs.join(",\n") + "\n}"
end
alias inspect to_s
alias [] get
alias []= set
private
def num_buckets
@store.length
end
def resize!
old_store = @store
@store = Array.new(num_buckets * 2) { DoublyLinkedList.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