summaryrefslogtreecommitdiff
path: root/misc/key-value-store/main.rb
blob: 2a4201405c10988bb501c29916976efb3726e6cc (plain)
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
def assert_equal(x, y)
  return if x == y

  raise "Expected `#{x.inspect}`, got `#{y.inspect}`"
end

class Store
  def initialize
    @hash = Hash.new do |hash, key|
      hash[key] = []
    end
  end

  # time: O(1) + O(logn)
  # space: O(1)
  def get(key, at: nil)
    bucket = @hash[key]
    return if bucket[-1].empty?

    if at
      bucket[-1].bsearch { |x| x <= at }[-1]
    else
      bucket[-1][-1]
    end
  end

  # time: O(1)
  # space: O(1)
  def set(key, value)
    @hash[key] << [Time.now.to_i, value]
  end
end

store = Store.new
store.set(:cart, 0)
now = Time.now.to_i
assert_equal(0, store.get(:cart))

store.set(:cart, 3)
assert_equal(3, store.get(:cart))

assert_equal(0, store.get(:cart, at: now))
puts "YAY!"