master
 1def assert_equal(x, y)
 2  return if x == y
 3
 4  raise "Expected `#{x.inspect}`, got `#{y.inspect}`"
 5end
 6
 7class Store
 8  def initialize
 9    @hash = Hash.new do |hash, key|
10      hash[key] = []
11    end
12  end
13
14  # time: O(1) + O(logn)
15  # space: O(1)
16  def get(key, at: nil)
17    bucket = @hash[key]
18    return if bucket[-1].empty?
19
20    if at
21      bucket[-1].bsearch { |x| x <= at }[-1]
22    else
23      bucket[-1][-1]
24    end
25  end
26
27  # time: O(1)
28  # space: O(1)
29  def set(key, value)
30    @hash[key] << [Time.now.to_i, value]
31  end
32end
33
34store = Store.new
35store.set(:cart, 0)
36now = Time.now.to_i
37assert_equal(0, store.get(:cart))
38
39store.set(:cart, 3)
40assert_equal(3, store.get(:cart))
41
42assert_equal(0, store.get(:cart, at: now))
43puts "YAY!"