Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class MyHashMap
BUCKETS = 100
attr_reader :iterations
def initialize
@values = []
@iterations = 0
end
def set(key, value)
key_bucket(key) << [key, value]
end
def get(key)
key_bucket(key).find do |v|
@iterations += 1
v[0] == key
end[1]
end
private
def key_bucket(key)
@values[bucket_number(key)] ||= []
end
def bucket_number(key)
key.chars.map(&:ord).inject(:+) % BUCKETS
end
end
map = MyHashMap.new
map.set 'key1', 'value1'
map.set 'key2', 'value2'
map.set 'key3', 'value3'
fail 'Nope' unless map.get('key1') == 'value1'
fail 'Nope' unless map.get('key2') == 'value2'
fail 'Nope' unless map.get('key3') == 'value3'
fail "#{map.iterations} iterations" if map.iterations > 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.