-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathstate.rb
More file actions
61 lines (47 loc) · 1.1 KB
/
state.rb
File metadata and controls
61 lines (47 loc) · 1.1 KB
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
class State
Update = Struct.new(:value, :diff)
def initialize(collect_history)
@state = {}
@timestamp = 0
@valid = true
@history = collect_history ? [] : nil
end
def get_state
list = []
@state.each do |key, value|
clone = JSON.parse(key)
value.times { list << clone }
end
list.freeze
end
def get_history
@history
end
private
def validate(timestamp)
raise "Invalid state." unless @valid
if timestamp < @timestamp
puts "Invalid timestamp."
@valid = false
raise "Update with timestamp (#{timestamp}) is lower than the last timestamp (#{@timestamp}). Invalid state."
end
end
def process(update)
# Count value starts as a NaN
value = JSON.generate(update[:value])
count = @state[value].to_i + update[:diff]
if count <= 0
@state.delete(value)
else
@state[value] = count
end
@history&.push(update)
end
public
def update(updates, timestamp)
return if updates.empty?
validate(timestamp)
@timestamp = timestamp
updates.each { |update| process(update) }
end
end